12 | Chapter 1: Foundational Techniques
The singleton class
Singleton classes(alsometaclassesoreigenclasses; see the upcoming sidebar, “Single-
ton Class Terminology”) allow an object’s behavior to be different from that of other
objects of its class. 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 # => "#<A:0x1cd0a0>"
objB.to_s # => "#<A:0x1c4e28>"
class <<objA # Open the singleton class of objA
def to_s; "Object A"; end
end
objA.to_s # => "Object A"
objB.to_s # => "#<A:0x1c4e28>"
Theclass <<objAnotation opensobjA’s singleton class. Instance methods added to
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