Singleton methods in Ruby live in a special, hidden class called the singleton class (it used to be referred to as the eigenclass, but singleton class is the current term). Singleton methods are only available for a certain instance, so they can’t be defined in the regular class like all the other instance methods. Ruby methods can only be defined in class objects, so singleton methods also cannot be defined in a regular object with the instance variables. Thus, singleton classes.
The singleton class can be accessed with two different syntaxes:
class A; end singleton_class = A.singleton_class # OR singleton_class2 = class << A self end singleton_class == singleton_class2 # => true
Class methods in Ruby are really just singleton methods for the class object. The following example shows how to use the shovel operator to define singleton methods for a class.
class B def self.first "One singleton method" end class << self def second "Another singleton method" end end end B.singleton_methods # => [:first, :second]
The rest of this blog post will refer to the singleton class of A as A’ (pronounced A prime).
Singleton classes inherit from other singleton classes. For example, if class B inherits from class A, B’ will inherit from A’ (remember, B’ stands for the singleton class of B and A’ stands for the singleton class of A).
class A class << self def whatever 'A.whatever' end end end class B < A; end p B.whatever # => 'A.whatever'