Introduction
suggest changeRuby has three types of objects:
- Classes and modules, which are instances of class
Classor classModule. - 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 the singleton class of object. Other Example instances cannot reply to foo.
Ruby creates singleton classes on demand. Accessing them or adding methods to them forces Ruby to create them.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents