Reputation: 22291
If I include a module into a class, which has initialize
defined, I can call it using super
:
module M
def initialize(x)
@m = x
end
end
class MyClass
def initialize
super(3)
end
def val
@m
end
end
MyClass.new.val
# => 3
But how do I code this, if I have several modules, and maybe also a parent class?
class Parent
def initialize(x)
@p = x
end
end
module M
def initialize(x)
@m = x
end
end
module N
def initialize(x)
@n = x
end
end
class MyClass < Parent
include M
include N
def initialize
# ???? How to initialize here?
end
def val
[@m,@n,@p]
end
end
I guess that super(100)
within MyClass::initialize
would set the variable @n
, because N
is the "most recent" ancestor, but how do I call the initialize
methods in M
and Parent
?
Upvotes: 3
Views: 185
Reputation: 15089
Take a look at this blog post (http://stdout.koraktor.de/blog/2010/10/13/ruby-calling-super-constructors-from-multiple-included-modules/). It explains how do you use the initialize
from different included modules.
Upvotes: 2