In Ruby, the singleton class is a powerful and sometimes mysterious feature that allows you to define methods for a single object, rather than for all instances of a class. This is particularly useful when you want to add behaviour to just one object, without affecting others.
What is a Singleton Class?
A singleton class (also known as a metaclass or eigenclass) is an anonymous class that is associated with a single object. When you define methods on a specific object using the def obj.method syntax or the class << obj construct, you are actually defining those methods on the object’s singleton class.
Why Use a Singleton Class?
To define class methods (since class methods are singleton methods on the class object).
To add behaviour to a single instance without affecting others.
To implement design patterns such as the Singleton pattern.
Create a simple object
greeting = "Hello"
# Add a singleton method to this object
def greeting.shout
upcase + "!"
end
puts greeting.shout # => "HELLO!"
# Another string does not have this method
farewell = "Goodbye"
# farewell.shout # This would raise NoMethodError
# You can also use the singleton class directly:
class << greeting
def whisper
downcase + "..."
end
end
puts greeting.whisper # => "hello..."
In this example, only the greeting object has the shout and whisper methods. Other string objects do not.
Conclusion
Ruby’s singleton class is a flexible tool for adding behaviour to individual objects. It is widely used in Ruby’s object model, especially for defining class methods and customising single instances. Understanding singleton classes can help you write more expressive and dynamic Ruby code.