Singleton classes are a powerful feature in Ruby that allow you to add methods to individual objects. They provide a way to extend or modify the behavior of specific instances without affecting other objects of the same class.
In Ruby, every object has its own hidden class called a singleton class (also known as eigenclass or metaclass). This class sits between the object and its regular class in the method lookup chain.
To define methods in a singleton class, you can use the class << object
syntax or the def object.method_name
shorthand. Here's an example:
obj = Object.new
class << obj
def singleton_method
puts "This is a singleton method"
end
end
# Or using the shorthand syntax:
def obj.another_singleton_method
puts "Another singleton method"
end
obj.singleton_method
obj.another_singleton_method
Singleton classes are particularly useful in the following scenarios:
Interestingly, when you define class methods in Ruby, you're actually working with the singleton class of the class object. This is why class methods are sometimes referred to as singleton methods of the class.
class MyClass
def self.class_method
puts "This is a class method"
end
end
# Equivalent to:
class << MyClass
def class_method
puts "This is a class method"
end
end
To deepen your understanding of Ruby's object model and metaprogramming capabilities, explore these related topics:
By mastering singleton classes, you'll gain a powerful tool for crafting flexible and dynamic Ruby code. Remember to balance their use with code readability and maintainability.