Singleton Methods

A singleton method is a method that belongs to a single object rather than to an entire class. Many of the methods in the Ruby class library are singleton methods. This is because, as mentioned earlier, each class is an object of the type Class. Or, to put it simply, the class of every class is Class. This is true of all classes—both those you define yourself and those provided by the Ruby class library:


class MyClass

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

Now, some classes also have class methods—that is, methods that belong to the Class object itself. In that sense, these are singleton methods of ...

Get The Book of Ruby now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.