Ruby设计模式问题 - 类/模块继承

时间:2010-12-30 00:56:46

标签: ruby oop class module

现在我有:

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应该是类变量还是模块下的常量?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

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指出的那样,你可以显式地传递你知道超类期望的任何参数。

有关继承的更多信息,请参阅Pickaxe书籍旧版但免费在线版本中的Inheritance and Messages部分。

答案 1 :(得分:2)

您需要super关键字。它会将您父母的定义称为相同的方法。

为了防万一,我添加了params。 注意,要传递参数B#initialize也必须使用可选参数。

module A   
  class C < B
    def initialize(params = nil)
       super(params) # calls B#initialize passing params
       @z = 'buzz'
    end   
  end
end