Prev | Current Page 25 | Next

Brad Ediger

"Advanced Rails"

You??™ve probably seen the notation to open up a singleton class
before:
class A
end
objA = A.new
objB = A.new
objA.to_s # => "#"
objB.to_s # => "#"
class <def to_s; "Object A"; end
end
objA.to_s # => "Object A"
objB.to_s # => "#"
The class <the singleton class function as instance methods in the lookup chain. The resulting
data structures are shown in Figure 1-8.
Figure 1-7. Ruby??™s solution for the diamond problem: linearization
A
C
B
super
D
super
klass
klass C
super
A
B
A
super
klass
klass
Ruby Foundations | 13
The objB instance is of class A, as usual. And if you ask Ruby, it will tell you that objA
is also of class A:
objA.class # => A
However, something different is going on behind the scenes. Another class object has
been inserted into the lookup chain. This object is the singleton class of objA. We
refer to it as ???Class:objA??? in this documentation. Ruby calls it a similar name:
#>. Like all classes, the singleton class??™s klass pointer (not
shown) points to the Class object.
The singleton class is marked as a virtual class (one of the flags is used to indicate that a
class is virtual). Virtual classes cannot be instantiated, and we generally do not see them
from Ruby unless we take pains to do so.


Pages:
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37