Ruby Language Introduction


Example

Ruby has three types of objects:

  • Classes and modules which are instances of class Class or class Module.
  • Instances of classes.
  • Singleton Classes.

Each object has a class which contains its methods:

class Example
end

object = Example.new

object.class  # => Example
Example.class # => Class
Class.class   # => Class

Objects themselves can't contain methods, only their class can. But with singleton classes, it is possible to add methods to any object including other singleton classes.

def object.foo
  :foo
end
object.foo #=> :foo

foo is defined on singleton class of object. Other Example instances can not reply to foo.

Ruby creates singleton classes on demand. Accessing them or adding methods to them forces Ruby to create them.