Class inheritance simply follows
the super pointers. For example, we will create a B class that descends from A:
class B < A
end
The resulting data structures are shown in Figure 1-2.
The super keyword always delegates along the method lookup chain, as in the following
example:
class B
def initialize
logger.info "Creating B object"
super
end
end
The call to super in initialize will follow the standard method lookup chain, beginning
with A#initialize.
Class instantiation
Now we get a chance to see how method lookup is performed. We first create an
instance of class B:
obj = B.new
This creates a new object, and sets its klass pointer to B??™s class object (see
Figure 1-3).
Figure 1-2. One level of inheritance
Object
A
super
B
super
8 | Chapter 1: Foundational Techniques
The single-bordered box around obj represents a plain-old object instance. Note that
each box in this diagram is an object instance. However, the double-bordered boxes
represent objects that are instances of the Class class (hence their klass pointer
points to the Class object).
When we send obj a message:
obj.to_s
this chain is followed:
1. obj??™s klass pointer is followed to B; B??™s methods (in m_tbl) are searched for a
matching method.
2. No methods are found in B. B??™s super pointer is followed, and A is searched for
methods.
3. No methods are found in A. A??™s super pointer is followed, and Object is searched
for methods.
Pages:
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33