Ruby - Class Singleton Methods


A singleton method is a method that belongs to a single object rather than to an entire class.

Each class is an object of the type Class.

The class of every class is Class.


class MyClass 
end # from  w w w. jav  a 2  s .  c  om

puts( MyClass.class )    #=> Class 
puts( String.class )     #=> Class 
puts( Object.class )     #=> Class 
puts( Class.class )         #=> Class 
puts( IO.class )         #=> Class


Class methods are singleton methods of the Class object.

Indeed, if you evaluate the following, you will be shown an array of method names that match the names of IO class methods:

p( IO.singleton_methods ) 

When you write your own class methods, you do so by prefacing the method name with the name of the class:

def MyClass.classMethod 

You can use a similar syntax when creating singleton classes for specific objects.

This time you preface the method name with the name of the object:

def myObject.objectMethod 

Related Topics