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.
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:
Singleton Method Example Invoke from train object: There are many wheels Invoke from car object: There are four wheels
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.
Singleton Method Example: Invoke from the object(o1): 13 Invoke from the object(o2): Size does not matter
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.
- Ruby | Methods
- Ruby Hook Methods
- Ruby | Dir Class and its methods
- Ruby | Range Class Methods
- Ruby | Exception Class and its Methods
- Ruby | Thread Class-Public Class Methods
- How to create singleton design pattern in PHP 5 ?
- ES6 | New String Methods
- Scala | Methods to Call on a Map | Set-1
- Difference between the Constructors and Methods
- Abstract Methods in Java with Examples
- GRE Data Analysis | Counting Methods
- How to create a jQuery plugin with methods?
- Difference between process.nextTick() and setImmediate() Methods
- Why does PHP 5.2+ disallow abstract static class methods ?
- HTTP headers | Access-Control-Allow-Methods
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.