Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the module initialize method not called?

Tags:

ruby

Why is this module's initialize method not called when it is included in Temp class?

module Temp
  def initialize
    p "asdasd"
  end
end

class Swap
  include Temp
  def initialize
    p "m in class"
  end
end

s = Swap.new

m in class

like image 341
swapnilp Avatar asked Jun 06 '12 06:06

swapnilp


1 Answers

The Swap class overrides the initialize method defined in the Temp module. When Ruby attempts to find a method it searches the inheritance hierarchy starting at the most derived class/module. In this case the search ends at the Swap class.

Overridden methods don't get called unless you explicitly call them with super. For example

class Swap
  include Temp
  def initialize
    p "m in  class"
    super
  end
end

will call Temp#initialize from Swap#initialize.

like image 106
Steve Avatar answered Sep 28 '22 00:09

Steve