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 is the output not "Hello qux"? credit for code

+4
source share
2 answers

When you include a module in a class, it acts like the ones into which you inserted the new superclass in the class hierarchy, only between Sample and Foo. Causes a super () search through the included modules before returning to the real superclass (Foo).

+10
source

The short answer is that it would be a crazy conversation if the result of this was "Hello World". The only two outputs that make any sense would be "Hello qux" or "qux World." In this case, "qux World" is the result because it is an order:

  • Sample extends Foo , initialize inherited from Foo
  • Sample includes Bar , initialize overridden
  • Sample defines initialize , which calls super , which indicates the most recent implementation of the ancestor initialize , in this case Bar 's

This will hopefully make it clearer:

 class Foo def initialize(a) puts "Hello #{a}" end end module Bar def initialize(b) super # this calls Foo initialize with a parameter of 'qux' puts "#{b} World" end end class Sample < Foo include Bar def initialize(c) super # this calls Bar initialize with a parameter of 'qux' end end Sample.new('qux') 

Output:

  Hello qux
 qux world
+2
source

All Articles