我希望一个子类从其父类继承一个类级实例变量,但我似乎无法弄清楚。基本上我正在寻找这样的功能:
class Alpha
class_instance_inheritable_accessor :foo #
@foo = [1, 2, 3]
end
class Beta < Alpha
@foo << 4
def self.bar
@foo
end
end
class Delta < Alpha
@foo << 5
def self.bar
@foo
end
end
class Gamma < Beta
@foo << 'a'
def self.bar
@foo
end
end
然后我希望它像这样输出:
> Alpha.bar
# [1, 2, 3]
> Beta.bar
# [1, 2, 3, 4]
> Delta.bar
# [1, 2, 3, 5]
> Gamma.bar
# [1, 2, 3, 4, 'a']
显然,这段代码不起作用。基本上我想为父类中的类级实例变量定义一个默认值,它的子类继承。子类的更改将成为子类的默认值。我希望这一切都发生,而不会改变一个类的值来影响其父级或兄弟级。Class_inheritable_accessor 给出了我想要的行为......但是对于一个类变量。
我觉得我可能要求太多了。有任何想法吗?