A Ruby class definition is just regular code that runs. When you use the class
keyword to create a class, you aren’t just dictating how objects will behave in the future. You are actually running code.
You can put any code in a class definition, and it returns the value of the last statement, just like methods and blocks do.
Inside the class definition, the class itself takes the role of the self
.
To access variables defined outside the class definition (i.e., flattening the scope), use class_eval
. Inside, you can also define new methods dynamically on the class, using define_method
.
Instance variables of a class (class instance variables) are different from the instance variables of that class’s objects. If you come from Java or C#, it’s tempting to think that the class instance variables are just the static fields of the class. Instead, they’re just regular instance variables of an object of class Class
.
The following example illustrates this. The class Ruby
is an object of the class Class
, whereas rb
is an object of the class Ruby
.
Singleton Methods
When you define a method on a class, e.g. Ruby.rails
, it’s also known as a singleton method of a class.
Here’s the syntax to define singleton method on an object. Here, object can be an object reference, a class name, or self.
Singleton Classes
A singleton class is where an object’s singleton methods live, whether that object is a class name or an object reference. You can access the singleton class by calling singleton_class
method on the object.
The superclass of the singleton class of an object is the object’s class.
The superclass of the singleton class of a class is the singleton class of the class’s superclass.
from: Metaprogramming Ruby 2