If we define two modules, with methods that have the same names
module M1 def foo puts "M1" end end module M2 def foo puts "M2" end end
and then include them in a class in a specific order
class C include M1 include M2 end
method from the last included module will be used.
C.new.foo # => "M2"
So it looks like the methods are “copied” into the including class, so that the last definition of “foo” gets precedence. That’s how I thought about including Ruby modules initially.
But if that was the case the following example
module M def foo puts "M" end end class C def foo puts "C" end include M end
should print “M”. But it doesn’t.
C.new.foo # => "C"
It calls the class “C” version of the “foo”, so the method can’t be redefined during the include.
What actually happens (and what I learned from “Include” part of Chapter 4 of Ruby Hacking Guide) is that the included module gets injected into the class hierarchy right above “C”.
class C def foo puts "C" super # Calling to see what the superclass defined. end end
Let’s check what the hierarchy looks like before the inclusion of M.
C.ancestors # => [C, Object, Kernel]
Now let’s define “M”
module M def foo puts "M" end end
and include it in “C”.
class C include M end
Let’s check how it affected the class hierarchy.
C.ancestors # => [C, M, Object, Kernel]
Module “M” got injected as a direct superclass of “C”.
C.new.foo # => "C" then "M"
As C#foo calls super it’s now obvious how we got that output.
look at my example and try to explaine result:
module B1
def printB
puts "B1"
end
end
module B2
def printB
puts "B2"
end
end
class C
include B2,B1
end
a=C.new
a.printB
For the record: the result of the code snippet posted by rumoku is “B2”.
Interesting. It’s easy to explain how of the result, but for the why you would have to ask Ruby developers. ;-)
Anyway, if you look at the source code for Module#include (rb_mod_include in eval.c), you’ll see that the arguments for include are processes backwards. So, “include B2, B1” is equivalent to “include B1; include B2”.
I agree it’s strange. Well, yet another Ruby quirk.
Perfect and simple explanation. thanks a lot mousebender
in your first example it’s possible to do this:
C.new.M1.foo
or how can i choose which one i can use?
Thanks
You can’t choose. M2 is before M1 in the ancestors list, so its implementation of foo will used. A solution is to either use different names for those methods or utilize composition instead of inheritance.
but with composition i wouldn’t have to change the modules to class, is that right?
Really depends on your case. You have to include the module somewhere: if not on class, you can directly extend an object with it.
Ok, thanks for the help i have tho figure what’s the best option.
Tiene buena pinta lo de las jornadas. u00bfMe puedo presentar con mi portu00e1til y mi Slack para demostrar que se puede tener un portu00e1il funciona Click https://twitter.com/moooker1