Ruby的include方法是什么?

4
class Foo
  def initialize(a)
    puts "Hello #{a}"
  end
end
module Bar
  def initialize(b)
    puts "#{b} World"
  end
end
class Sample < Foo
  include Bar
  def initialize(c)
    super
  end
end
Sample.new('qux') #=> qux World

为什么输出不是'Hello qux'? 代码来源
2个回答

10

当你将一个模块包含到一个类中时,它就像是在类层次结构中插入了一个新的超类,位于Sample和Foo之间。调用super()会在回退到真正的超类(Foo)之前搜索包含的模块。


2
简短回答是,如果输出结果是“Hello World”,那就绝对是荒唐的说法。只有两个输出结果是有意义的,分别是“Hello qux”或“qux World”。在这种情况下,“qux World”是输出结果,因为执行顺序如下:
  1. Sample 继承自 FooinitializeFoo 继承
  2. Sample 包含 Barinitialize 被覆盖
  3. Sample 定义 initialize,并调用 super,指向最近祖先的 initialize 实现,在这种情况下,是 Bar 的实现
希望这样更加清晰明了。
class Foo
  def initialize(a)
    puts "Hello #{a}"
  end
end
module Bar
  def initialize(b)
    super # this calls Foo's initialize with a parameter of 'qux'
    puts "#{b} World"
  end
end
class Sample < Foo
  include Bar
  def initialize(c)
    super # this calls Bar's initialize with a parameter of 'qux'
  end
end
Sample.new('qux')

输出:

你好 qux
qux 世界

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接