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

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

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.