【发布时间】:2014-02-03 01:15:32
【问题描述】:
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
【问题讨论】:
-
attr_accessor 是 ruby 在对象实例(以及实例变量)上创建 setter 和 getter 的简写,不适用于类级变量
-
虽然我对 Rails 几乎一无所知,但我相信
require 'active_support',你可以使用cattr_accessor :things。
标签: ruby