Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby include question

Tags:

ruby

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

like image 728
Roger Avatar asked Dec 17 '22 05:12

Roger


1 Answers

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

like image 71
Jonathan del Strother Avatar answered Jan 01 '23 04:01

Jonathan del Strother