Ruby - Class Singleton Methods

Introduction

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.

Demo

class MyClass 
end #  www. j av a2  s  .co  m

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

Result

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