Skip to content

idiom: Singleton Class

jtigger edited this page Nov 28, 2010 · 1 revision

singleton class

Idiom:

(class << some_object; self; end)

is best understood in two steps:

first, this part (i.e. minus the "self" in the middle:)

(class << some_object; ... ; end)

means: create a secret class for the object pointed to by "some_object". This is known as a "singleton class" or a "metaclass". It's a class without a name and "some_object" becomes an instance of that class.

But, because the new class has no name, we've got a problem... how do we reference it (we might want to do this to, say, add a new method to this new class)? We get the reference by including the self inside the class definition. When the whole expression executes, the "self" is the return value:

new_class = (class << some_object; self; end)  # value of this expression is the new class
new_class.to_s                                  # => something like "#<Class:#<Array:0x71c50>>"

Here's a more in-depth explanation: http://wanderingbarque.com/ruby/DynamicRuby.html

Clone this wiki locally