Ruby - Class Singleton Classes


A singleton method is a method that belongs to a single object.

A singleton class is a class that defines a single object.

ob = # singleton class 
class << ob 
    def sayHi( aStr ) 
        puts("sayHi, sayHi #{aStr}") 

Here, ob, and only ob, has not only all the usual methods of the Object class.

It also has the methods of its own special anonymous class:

ob.sayHi( "abc" )    #=> "sayHi, sayHi abc" 

With a singleton class, you can create an object and then add extra methods packaged up inside an anonymous class.

With singleton methods, I can create an object and then add methods one by one:

ob2 = 

def ob2.sayHi( aStr )        # <= this is a singleton method 
   puts( "hi, hi #{aStr}" ) 

ob2.sayHi( "ping!" )         #=> hi, hi ping! 

The following code created a singleton class containing the congratulate method:

myBox = "Star Prize" ) 

class << myBox 
   def congratulate 
      puts( "hi!" ) 

The end result of the previous code is that congratulate becomes a singleton method of myBox.

You can verify this by checking whether the array of singleton methods available for the item object contains the name congratulate:

if item.singleton_methods.include?(:congratulate)    # Ruby 1.9 

In Ruby 1.9, the singleton_methods method returns an array of symbols representing the method names.

In Ruby 1.8, singleton_methods returns an array of strings.

If you are using Ruby 1.8, you should be sure to use the following test using the string argument "congratulate":

if item.singleton_methods.include?("congratulate")    # Ruby 1.8 


What's the difference between a singleton method and a singleton class?

Not a lot.

These two syntaxes provide different ways of adding methods to a specific object rather than building those methods into its class.

Related Topics