类变量上的 Attr_accessor [英] Attr_accessor on class variables
问题描述
attr_accessor
不适用于以下代码.错误说undefined method 'things' for Parent:Class (NoMethodError)
":
attr_accessor
does not work on the following code. The error says "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
推荐答案
attr_accessor
定义实例的访问器方法.如果你想要类级自动生成的访问器,你可以在元类上使用它
attr_accessor
defines accessor methods for an instance. If you want class level auto-generated accessors you could use it on the metaclass
class Parent
@things = []
class << self
attr_accessor :things
end
end
Parent.things #=> []
Parent.things << :car
Parent.things #=> [:car]
但请注意,这会创建一个类级别的实例变量不是一个类变量.无论如何,这可能是您想要的,因为类变量的行为与您在处理继承时可能期望的不同.请参阅Ruby 中的类和实例变量".
but note that this creates a class level instance variable not a class variable. This is likely what you want anyway, as class variables behave differently then you might expect when dealing w/ inheritence. See "Class and Instance Variables In Ruby".
这篇关于类变量上的 Attr_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!