attr_accessor不适用于以下代码.错误说" undefined method 'things' for Parent:Class (NoMethodError)":
class Parent
  @@things = []
  attr_accessor :things
end
Parent.things << :car
p Parent.things
但是以下代码有效
class Parent
  @@things = []
  def self.things
    @@things
  end
  def things
    @@things
  end
end
Parent.things << :car
p Parent.things
Ale*_*ard 89
attr_accessor定义实例的访问器方法.如果您需要类级别自动生成的访问器,则可以在元类上使用它
class Parent
  @things = []
  class << self
    attr_accessor :things
  end
end
Parent.things #=> []
Parent.things << :car
Parent.things #=> [:car]
但请注意,这会创建一个类级实例变量而不是类变量.这很可能是你想要的,因为类变量的行为与你在处理w/inheritence时可能会有的不同.请参阅" Ruby中的类和实例变量 ".
Chu*_*uck 15
attr_accessor为实例变量生成访问器.Ruby中的类变量是一个非常不同的东西,它们通常不是你想要的.你可能想要的是一个类实例变量.您可以使用attr_accessor类实例变量,如下所示:
class Something
  class <<self
    attr_accessor :things
  end
end
然后你可以写Something.things = 12,它会工作.
只是一些澄清:类变量将无法使用attr_accessor. 这都是关于实例变量的:
class SomeClass
  class << self
    attr_accessor :things
  end
  @things = []
end
因为在 Ruby 中,类是类“Class”(上帝,我喜欢这么说)的实例,并attr_accessor为实例变量设置访问器方法。
这可能是最简单的方法。
class Parent
  def self.things
    @@things ||= []
  end
end
Parent.things << :car
p Parent.things
| 归档时间: | 
 | 
| 查看次数: | 46106 次 | 
| 最近记录: |