class Foo
class << self
attr_accessor :var
end
end
class Bar < Foo
var = "bar"
p var # print "bar"
end
p Bar.var # print nil
为什么Bar.var没有返回“bar”?
如何为类变量添加getter / setter?
答案 0 :(得分:1)
class Bar < Foo
var = "bar" # this is assignment to local variable, not the accessor
end
使用self
告诉ruby您要调用该方法,而不是创建局部变量。
class Foo
class << self
attr_accessor :var
end
end
class Bar < Foo
self.var = "bar"
var # => "bar"
end
Bar.var # => "bar"