chapter thirteen

13 Object individuation

 

This chapter covers

  • Singleton methods and classes
  • Class methods
  • The extend method
  • Overriding Ruby core behavior
  • The BasicObject class

One of the cornerstones of Ruby’s design is object individuation—that is, the ability of individual objects to behave differently from other objects of the same class. Every object is a full-fledged citizen of the runtime world of the program and can live the life it needs to.

The freedom of objects to veer away from the conditions of their birth has a kind of philosophical ring to it. On the other hand, it has some important technical implications. A remarkable number of Ruby features and characteristics derive from or converge on the individuality of objects. Much of Ruby is engineered to make object individuation possible. Ultimately, the individuation is more important than the engineering: Matz has said over and over again that the principle of object individuality is what matters, and how Ruby implements it is secondary.

Still, the implementation of object individuation has some powerful and useful components. The ability to treat like objects differently under given conditions can keep your code more nimble, prevent unnecessary duplication or the creation of very similar objects, and open up powerful metaprogramming techniques.

13.1 Where the singleton methods are: the singleton class

13.1.1 Dual determination through singleton classes

13.1.2 Examining and modifying a singleton class directly

13.1.3 Singleton classes on the method-lookup path

13.1.4 Class methods in (even more) depth

13.1.5 Per-object changes with extend

13.1.6 Adding to a (non-class) object’s functionality with extend

13.2 Modifying Ruby’s core classes and modules

13.2.1 The risks of changing core functionality

13.2.2 Additive changes

13.2.3 Pass-through overrides

13.2.4 Modifying core behavior with extend

13.2.5 Using refinements to affect core behavior

13.3 BasicObject as ancestor and class

13.3.1 Using BasicObject

13.3.2 Implementing a subclass of BasicObject

13.4 Summary