这是我设法做到这一点的一种方式。
class Test
class << self
attr_accessor :stuff
def thing msg
@stuff ||= ""
@stuff += msg
end
end
def initialize
@stuff = self.class.stuff
puts @stuff
end
end
# Is there a better way of accomplishing this?
class AThing < Test
thing "hello"
thing "world"
end
AThing.new
# Prints "helloworld"
AThing 中的界面是我想要的最终结果。我真正讨厌(而且我觉得必须有更好的方法来完成)是@stuff = self.class.stuff。
有没有更好的方法来使用 eigenclass 为自身的所有实例设置默认数据集,同时保持“漂亮”的界面?
我想用这样的代码完成的是有一个类方法,比如 add_something ,它将一些东西添加到存储在类变量中的数组中。
当类被实例化时,它将在其初始化方法中使用此数组来设置该实例的状态。