Ruby resolves this by linearizing the order of inclusion. Upon a method call,
the lookup chain is searched linearly, including any ICLASSes that have been
inserted into the chain.
First of all, Ruby does not support multiple inheritance; however, multiple modules
can be mixed into classes and other modules. Therefore, A, B, and C must be modules.
We see that there is no ambiguity here; the method chosen is the latest one that
was inserted into the lookup chain:
module A
def hello
"Hello from A"
end
end
Figure 1-5. Method lookup for a class with an included module
Object
Mixin
super
A
super
Mixin klass
objA klass
Ruby Foundations | 11
module B
include A
def hello
"Hello from B"
end
end
module C
include A
def hello
"Hello from C"
end
end
class D
include B
include C
end
D.new.hello # => "Hello from C"
And if we change the order of inclusion, the result changes correspondingly:
class D
include C
include B
end
D.new.hello # => "Hello from B"
In this last example, where B is included last, the object graph looks like Figure 1-7
(for simplicity, pointers to Object and Class have been elided).
Figure 1-6. The diamond problem of multiple inheritance
A
B C
D
12 | Chapter 1: Foundational Techniques
The singleton class
Singleton classes (also metaclasses or eigenclasses; see the upcoming sidebar, ???Singleton
Class Terminology???) allow an object??™s behavior to be different from that of other
objects of its class.
Pages:
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36