开发者

ruby include question

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

Why output is not 'Hello qux' ? credit for code


When you include a module into a class, it acts as those you've inserted a new superclass in the class hierarchy, just between Sample and Foo. Calls to super() hunt through included modules before falling back to the real superclass (Foo).


The short answer is that it would be absolute crazy talk if the output of that was "Hello World". The only two outputs that make any sense at all would be "Hello qux" or "qux World". In this case, "qux World" is the output because this is the order:

  1. Sample extends Foo, initialize inherited from Foo
  2. Sample includes Bar, initialize overridden
  3. Sample defines initialize, which calls super, which points to the most recent ancestor's implementation of initialize, in this case, Bar's

This should hopefully make it more clear:

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')

Output:

Hello qux
qux World
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜