tags:

views:

869

answers:

2
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

+8  A: 

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

jdelStrother
+1  A: 

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
Bob Aman