现在我有:
module A
class B
def initialize
@y = 'foo'
end
end
end
module A
class C < B
def initialize
@z = 'buzz'
end
end
end
当我实例化 C 时,如何才能让 @y 仍然设置为“foo”?我是否必须在 C 下的初始化中重复该操作?我正在遵循一个坏模式? @y 应该是类变量还是模块下的常量?任何帮助将不胜感激!
最佳答案
class A::C < B
def initialize( x, y )
super # With no parens or arguments, this passes along whatever arguments
# were passed to this initialize; your initialize signature must
# therefore match that of the parent class
@z = 'buzz'
end
end
或者,正如@EnabrenTane 指出的那样,您可以显式传递您知道父类(super class)期望的任何参数。
有关继承的更多信息,请参阅 Inheritance and Messages 部分在 Pickaxe 书的旧但免费的在线版本中。
关于Ruby 设计模式问题 - 类/模块继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559194/