Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to ‘class?’ The concept is fuzzy, but I believe it has something to do with why I can define a class method at all (class foo; def foo.bar ...).
What is the singleton class in Ruby?
First, a little definition: a singleton method is a method that is defined only for a single object. Example:
Instance methods are methods of a class (i.e. defined in the class’s definition). Class methods are singleton methods on the
Classinstance of a class — they are not defined in the class’s definition. Instead, they are defined on the singleton class of the object.You open the singleton class of an object with the syntax
class << obj. Here, we see that this singleton class is where the singleton methods are defined:So an alternative means of adding singleton methods to an object would be to define them with the object’s singleton class open:
In summary:
Class