liveBook · Manning

Object individuation

As explained in The Well-Grounded Rubyist, Fourth Edition

Object individuation is the practice of giving selected Ruby objects additional methods or capabilities tailored to their runtime circumstances.

Object individuation lets individual Ruby objects behave differently from other objects of the same class. Ruby treats an object's class as only part of its behavior, leaving room for runtime-specific methods and capabilities. section 13.0 section 3.8

Giving one object a method

mag = Magazine.new def mag.wings puts "Look! I can fly!" end mag.wings #1 The method belongs to mag rather than automatically becoming available to every Magazine instance. section 3.8

Use this technique carefully and selectively. Its strongest cases arise when runtime conditions determine behavior, such as adding accessors for database columns discovered during execution or granting special methods to only certain strings. section 3.8

Ruby's per-object behavior supports several related techniques:

  • Singleton methods attach methods to individual objects. section 13.0
  • Singleton classes store singleton method definitions. section 13.0
  • Class methods are singleton methods attached to class objects. section 3.8 section 13.0
  • The extend method provides module-based behavior to one object at a time. section 13.0

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the rationale, singleton methods, singleton classes, class methods, and extend, while stopping short of their detailed implementation.
Examples
Demonstrates a Magazine object gaining a wings method and considers dynamic database accessors and special string methods.
What it assumes
Assumes familiarity with Ruby objects and classes while treating modules as the next related construct.
What you can do after
Apply singleton methods and extend to give selected objects runtime-specific behavior without changing every instance.
How it connects
Connects singleton methods, singleton classes, class methods, modules, extend, metaprogramming, and object classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.