Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ruby – Singleton Methods

  • Last Updated : 03 Jul, 2020

Ruby’s singleton methods are the methods that can be defined for a specific object only i.e. it works for a single object. These kinds of methods belong to the singleton class or eigenclass and are available exclusively for a single object, unlike the other methods which are available for all the instances of the class.

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.
Syntax:

def Obj.GFG
# Method body 
end

Here, the GFG is a singleton method and Obj is an object.
The concept of Singleton methods can be understood by the following examples:
Example 1:




# 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

Output:

Singleton Method Example
Invoke from train object:
There are many wheels
Invoke from car object:
There are four wheels

Explanation:
It can be observed that the method wheels have been redefined for the car object of Vehicle class. This wheels method is nothing but a singleton method that shows different behavior for the car.



Example 2:




# Ruby program to demonstrate the use 
# of singleton methods
o1 = String.new 
  
# object1(o1)
o1 = "GeeksforGeeks"
o2 = String.new 
  
# object2(o2)
o2 = "GoodExample"
  
# Singleton method of object o2 
def o2.size     
 return "Size does not matter"
end
   
puts "Singleton Method Example:"
puts "Invoke from the object(o1):"
  
# Returns the size of string "Example1"
puts o1.size 
puts "Invoke from the object(o2):"
  
# Returns the o2.size method’s
# return statement
puts o2.size 

Output:

Singleton Method Example:
Invoke from the object(o1):
13
Invoke from the object(o2):
Size does not matter

Explanation:
Singleton method can be defined for the objects which belong to library classes such as String. Instead of printing the size of Object o2, the above code is printing “Size does not matter!” because this is the return value of the o2.size method.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!