Skip to Content

Singleton class/method in Ruby

Posted on

Singleton

  • Allow define methods that are only available on a single object rather than all instances of a class.

Singleton Class

class MyClass
end

obj = MyClass.new

# Define a method only for this object
class << obj
  def singleton_method
    p "Singleton Method"
  end
end

obj.singleton_method
p "-" * 30

# This will raise error because the singleton method is defined only for obj
another_obj = MyClass.new
another_obj.singleton_method

class << obj opens the Singleton class of obj. Methods in this class are only available on obj and not on other instances of MyClass

Singleton Methods

class MyClass
end

obj = MyClass.new

# Define a method only for this specific object
def obj.singleton_method
  "I am a singleton method"
end

puts obj.singleton_method  # Output: "I am a singleton method"

# This will raise an error because other instances do not have this method
another_obj = MyClass.new
# puts another_obj.singleton_method

Conclusion

  • Singleton Class: A class created by Ruby for each object, allowing methods to be defined only on that object.
  • Singleton Method: A method defined for a single object, making it unique to that object.
comments powered by Disqus