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

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

最佳答案

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/

相关文章:

java - 无法在Eclipse IDE中执行Java代码

oop - TPL DataFlow 和架构设计

R 引用类 - 如何确定您是否在继承方法中?

ruby-on-rails - 无法在 Rails 应用程序的 lib 文件夹中使用定义的类

python - 获取 Python Tkinter 对象类型

C# 构造函数链接 : proper usage?

ruby-on-rails - 没有路由匹配 [GET] "demo/hello"

Ruby 1.9 - 无效的多字节字符 (utf-8)

ruby-on-rails - 计算两个 Time 对象之间的时间差

ruby - 如何在 rails_admin 的编辑表单中隐藏 "Save and Add Another"按钮?