Three different methodsSingleton MethodWhat are they?Why do we need them?Example from geeksforgeeksHow to use them?Another way to create singleton methodA class method is also a singleton method for itselfRelated Articles
Three different methods
- Instance methods (accessible for only that instance)
- Class methods (accessible for all instances)
- Singleton methods (only that object has that method)
class Foo
def an_instance_method
puts "I am an instance method"
end
def self.a_class_method
puts "I am a class method"
end
end
foo = Foo.new
def foo.a_singleton_method
puts "I am a singleton method"
end
Singleton Method
What are they?
- Singleton class: a class that only has one instance
- Singleton method: a method that can be defined for a specific object only
Why do we need them?
This feature is more useful where there is a need for the object to possess some unique behavior or methods which the other objects of the class do not own.
Example from geeksforgeeks
# Ruby program to demonstrate the use
# of singleton methods
class Vehicle
def wheels
puts "There are many wheels"
end
end
# Object train
train = Vehicle.new
# Object car
car = Vehicle.new
# Singleton method for car object
def car.wheels
puts "There are four wheels"
end
puts "Singleton Method Example"
puts "Invoke from train object:"
train.wheels
puts "Invoke from car object:"
car.wheels
# Singleton Method Example
# Invoke from train object:
# There are many wheels -> can not access car.wheels
# Invoke from car object:
# There are four wheels
“The real problem with Singletons is that they give you such a good excuse not to think carefully about the appropriate visibility of an object.” – Kent Beck
How to use them?
- Ruby has
Singleton
module
class Object
include Singleton
def singleton_method
end
end
# create an object
Object.new
# access that instance
Object.instance
Object.instance.object_id
Object.instance.singleton_method
Another way to create singleton method
foo = Foo.new
class << foo
def a_singleton_method
puts "I am a singleton method"
end
end
A class method is also a singleton method for itself
class Foo
class << self
def a_singleton_and_class_method
puts "I am a singleton method for self and a class method for Foo"
end
end
end