How a Ruby class to initialize all included modules? -


see following sample code first:

module first   def initialize     puts "second init"   end    def first     puts "first"   end end  module second   def initialize     puts "second init"   end    def second     puts "second"   end end  class myclass   include first   include second    def initialize     super()   end end  c = myclass.new c.first c.second 

output of program is:

second init first second 

from output, can see myclass has included first , second modules, because has both first() , second() methods.

in myclass constructor, try initialize both included modules super(), seems second's constructor called.

how initialize included modules?

include inserts module in between present class , ancestors. since first, second included, ancestors of myclass is

[myclass, second, first, ...] 

the keyword super looks first method available in ancestor class besides own class. , finds second#initialize.

if want accumulate initialize methods of ancestor modules, this:

module first   def initialize     puts "second init"   end end  module second   include first   def initialize     super     puts "second init"   end end  class myclass   include second   def initialize     super   end end 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -