Singleton Methods and the Eigenclass

We learned in Chapter 6 that it is possible to define singleton methods—methods that are defined for only a single object rather than a class of objects. To define a singleton method sum on an object Point, we’d write:

def Point.sum
  # Method body goes here
end

As noted earlier in this chapter, the class methods of a class are nothing more than singleton methods on the Class instance that represents that class.

The singleton methods of an object are not defined by the class of that object. But they are methods and they must be associated with a class of some sort. The singleton methods of an object are instance methods of the anonymous eigenclass associated with that object. “Eigen” is a German word meaning (roughly) “self,” “own,” “particular to,” or “characteristic of.” The eigenclass is also called the singleton class or (less commonly) the metaclass. The term “eigenclass” is not uniformly accepted within the Ruby community, but it is the term we’ll use in this book.

Ruby defines a syntax for opening the eigenclass of an object and adding methods to it. This provides an alternative to defining singleton methods one by one; we can instead define any number of instance methods of the eigenclass. To open the eigenclass of the object o, use class << o. For example, we can define class methods of Point like this:

class << Point def class_method1 # This is an instance method of the eigenclass. end # It is also a class method of Point. def class_method2 ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.