Give one string its own method
str = "I am a string" class << str def twice self + " " + self end end puts str.twice # I am a string I am a string The definition belongs to str alone, not to every String instance. section 13.1.2
A singleton class is an object’s exclusive place for singleton methods. `class << object` opens that class’s definition body; ordinary instance-method definitions inside it become methods callable on the specified object. The object can still use methods from its original class, ancestors, and mixed-in modules. section 13.1.1 section 13.1.2
The notation connects several familiar Ruby techniques:
- `def str.twice` also defines a singleton method. The two forms usually behave alike, but constants inside their method definitions can resolve differently. section 13.1.2
- Inside a class definition, `class << self` opens the class object’s singleton class. Methods defined there are class methods; grouping several definitions this way avoids repeating `def self.method_name`. section 5.1.3
- `include` inside an object’s singleton class adds a module to that object’s lookup path. `object.extend(Module)` produces the same method-lookup effect, though `include` and `extend` trigger different callbacks. section 13.1.5 section 15.1.3
Share behavior without changing every instance
module Secretive def name "[not available]" end end class << ruby include Secretive end If ruby is a Person instance, its `name` lookup now reaches Secretive. Other Person instances retain their usual `name` behavior. `ruby.extend(Secretive)` is the shorter alternative when adding the module is all you need. section 13.1.3 section 13.1.6
Lookup checks modules prepended to the singleton class, then the singleton class itself, then modules included there, before continuing to the object’s original class. Class objects have a further wrinkle: a subclass’s singleton class inherits from its parent class’s singleton class, so subclasses can call inherited class methods. section 13.1.3 section 13.1.4
Figure 13.1 Method-search order, revised to include singleton classes
Follow the revised method-search path to see where an object’s singleton class and its included modules sit relative to the original class. section 13.1.3
To inspect the result, use `object.singleton_class.ancestors` for the lookup chain or `object.singleton_methods` for public and protected singleton methods. The latter omits private ones. Not every object can acquire singleton methods: integers, floats, and symbols are exceptions. section 13.1.3 section 15.2.4 section 13.1
