Home »
Ruby Tutorial
Singleton Methods in Ruby
By IncludeHelp Last updated : November 16, 2024
In the last tutorial frozen objects, we have studied the way to freeze the objects in Ruby. We can't assign singleton methods to the objects which are frozen but what are Singleton methods, what are the properties they possess and how they are created? You will get the answer to all the above-raised questions in the rest of the content of this article. After successfully reading the tutorial, you will be very well aware of the things which are essential to understand Singleton methods in Ruby.
Ruby Singleton Methods
We know that the behavior of an object is decided by the class it belongs to. It simply means that the instance will be able to invoke the methods which are defined in that particular class. But sometimes we want that our object should possess some unique behavior or our object should have a method which other objects of the same class do not have. In this scenario, singleton methods come into the scene. Singleton methods are used in the Graphical user interface where different operations are performed at the click event of different buttons. In Ruby, we have the privilege to provide objects their methods or you can say that we can define singleton methods in Ruby.
For a better understanding of the concept, let us understand this with the help of illustrating program codes.
Example 1
=begin
Ruby program to demonstrate singleton methods
=end
class Example
def prnt
puts "Go Corona! Corona Go!"
end
end
object1 = Example.new
object2 = Example.new
def object2.prnt
puts "Corona bhag jaa!"
end
puts "singleton method demonstration"
puts "Invoke from object1:"
object1.prnt
puts "Invoke from object2:"
object2.prnt
Output
singleton method demonstration
Invoke from object1:
Go Corona! Corona Go!
Invoke from object2:
Corona bhag jaa!
Explanation
In the above code, you can observe that we have redefined a method prnt for object2 of Example class. That prnt method is nothing but a singleton method that is behaving differently for the object2.
Example 2
=begin
Ruby program to demonstrate singleton methods
=end
object1 = String.new
object1 = "includehelp"
object2 = String.new
object2 = "hrithik"
def object2.size
return "Corona bhag jaa!"
end
puts "singleton method demonstration"
puts "Invoke from object1:"
puts object1.size
puts "Invoke from object2:"
puts object2.size
Output
singleton method demonstration
Invoke from object1:
11
Invoke from object2:
Corona bhag jaa!
Explanation
In the above code, you can observe that we can define the singleton method for the objects which belong to library classes. Instead of printing the size of object2, our code is printing "Corona bhag jaa! because this is returned by the method.