class TestController < ApplicationController
  def test
    @goodbay = TestClass.varible
  end
end
class TestClass
  @@varible = "var"
end
我得到错误
undefined method 'varible' for TestClass:Class 
在线上 @goodbay = TestClass.varible 
怎么了?
Phr*_*ogz 23
在Ruby中,必须通过该对象上的方法读取和写入对象的@instance变量(和@@class变量).例如:
class TestClass
  @@variable = "var"
  def self.variable
    # Return the value of this variable
    @@variable
  end
end
p TestClass.variable #=> "var"
Ruby有一些内置方法可以为您创建简单的访问器方法.如果要在类上使用实例变量(而不是类变量):
class TestClass
  @variable = "var"
  class << self
    attr_accessor :variable
  end
end
Ruby on Rails提供了一种专门用于类变量的便捷方法:
class TestClass
  mattr_accessor :variable
end
小智 9
这是另一个选择:
class RubyList
  @@geek = "Matz"
  @@country = 'USA'
end
RubyList.class_variable_set(:@@geek, 'Matz rocks!')
puts RubyList.class_variable_get(:@@geek)
您必须正确访问类变量。其中一种方式如下:
class TestClass
  @@varible = "var"
  class << self
    def variable
      @@varible
    end
  end
 # above is the same as
 # def self.variable
 #   @@variable
 # end
end
TestClass.variable
#=> "var"
| 归档时间: | 
 | 
| 查看次数: | 24105 次 | 
| 最近记录: |