concept singleton class in category ruby

appears as: singleton classes, singleton class, singleton classes, singleton class
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

You’re familiar from chapter 3 with the singleton method—a method defined directly on an object (def obj.talk)—and you may wonder where in the method-lookup path singleton methods lie. The answer is that they lie in a special class, created for the sole purpose of containing them: the object’s singleton class. We’ll look at singleton classes in detail later in the book, at which point we’ll slot them into the method-lookup model.

We’ll look in this chapter at how Ruby goes about allowing objects to acquire methods and behaviors on a per-object basis, and how the parts of Ruby that make per-object behavior possible can be used to greatest advantage. We’ll start by examining in detail singleton methods—methods that belong to individual objects—in the context of singleton classes, which is where singleton method definitions are stored. We’ll then discuss class methods, which are at heart singleton methods attached to class objects. Another key technique in crafting per-object behavior is the extend method, which does something similar to module inclusion but for one object at a time. We’ll look at how you can use extend to individuate your objects.

But to get inside the definition body of a singleton class, you use a special notation:

class << object
  # method and constant definitions here
end

The << object notation means the anonymous, singleton class of object. When you’re inside the singleton class–definition body, you can define methods—and these methods will be singleton methods of the object whose singleton class you’re in.

Recall that method searching goes up the class-inheritance chain, with detours for any modules that have been mixed in or prepended. When we first discussed this process, we hadn’t talked about singleton classes and methods, and they weren’t present in the diagram. Now we can revise the diagram to encompass them, as shown in figure 13.1.

Figure 13.1. Method-search order, revised to include singleton classes

The box containing class << object represents the singleton class of object. In its search for the method x, object looks first for any modules prepended to its singleton class; then it looks in the singleton class itself. It then looks in any modules that the singleton class has included. (In the diagram, there’s one: the module Y.) Next, the search proceeds up to the object’s original class (class D), and so forth.

Note in particular that it’s possible for a singleton class to prepend or include a module. After all, it’s a class.