Singleton Classes

Where you place the final piece in the object model puzzle.

Singleton classes are the UFOs of the Ruby world: even if you never see one in person, you can find scattered hints of their existence all over the place. Let’s start our investigation into this difficult subject by collecting some evidence. (Be aware that the next few pages contain advanced material that might take a while for you to digest. If you want, you can skip straight to Method Wrappers, on your first read through and come back to this section later.)

The Mystery of Singleton Methods

In Method Lookup, you learned how Ruby finds methods by going right into the receiver’s class and then up the class hierarchy. For example:

 class​ MyClass
 def​ my_method; ...

Get Metaprogramming Ruby 2 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.