Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Ruby Foundations | 13

TheobjBinstance is of classA, as usual. And if you ask Ruby, it will tell you thatobjA
is also of classA:


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 ofobjA.We
refer to it as “Class:objA” in this documentation. Ruby calls it a similar name:
#<Class:#>. Like all classes, the singleton class’sklasspointer (not
shown) points to theClass object.


The singleton class is marked as avirtual class(one of theflags 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. When we ask Ruby forobjA’s class, it traverses
theklassandsuperpointers up the hierarchy until it finds the first nonvirtual class.


Figure 1-8. Singleton class of an object


Singleton Class Terminology
The termmetaclassis not particularly accurate when applied to singleton classes. Call-
ing a class “meta” implies that it is somehow more abstract than an ordinary class. This
is not the case; singleton classes are simply classes that belong to a particular instance.
True metaclasses are found in languages such as Smalltalk that have a rich metaobject
protocol. Smalltalk’s metaclasses are classes whose instances are classes. By parallel,
Ruby’s only metaclass is Class, because all Ruby classes are instances of Class.
A somewhat popular alternate term for a singleton class iseigenclass, from the German
eigen (“its own”). An object’s singleton class is its eigenclass (its own class).

Object

A

super

Class:objA
(virtual)

super

objA klass

objB klass
Free download pdf