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:
Sample
extendsFoo
,initialize
inherited fromFoo
Sample
includesBar
,initialize
overriddenSample
definesinitialize
, which callssuper
, which points to the most recent ancestor's implementation ofinitialize
, 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
精彩评论