A Singleton Class is a hidden class that all objects in Ruby can have. The Singleton Class is associated with a single object and not shared by all object of the same type/class. Look at it this way, if we have two instances of strings:
Which may look strange, but what is happening is your are switching context to the obj's Singleton Class with "class << obj;"..."end". Then within that context, you are returning "self" which references the Singleton Class inside that context.
RCR231 suggests the following Kernal method to make access easy:
module Kernel unless Kernel.respond_to? :singleton_class def singleton_class class << self; self; end end end end
Outstanding Questions...
What is the difference between "class Foo; def Foo.bar; 1; end; end" and "class Foo; class << self; def bar; 1; end; end; end"? As far as I can find, they are exactly the same.
Why doesn't "x.singleton_class.methods - Class.methods" return any methods? It seems methods defined in the Singleton Class context magically appear on the object's method list (e.g. x.methods).