Introduction

suggest change

Ruby has three types of objects:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents