Prev | Current Page 18 | Next

Brad Ediger

"Advanced Rails"

Modules can be used as
mixins??”bundles of functionality that are added onto a class to add behaviors in lieu
of multiple inheritance. Modules are also used to separate classes into namespaces.
In Ruby, every class name is a constant. This is why Ruby requires class names to
begin with an uppercase letter. The constant evaluates to the class object, which is an
object of the class Class. This is distinct from the Class object, which represents the
actual class Class.* When we refer to a ???class object??? (with a lowercase C), we mean
any object that represents a class (including Class itself). When we refer to the ???Class
object??? (uppercase C), we mean the class Class, which is the superclass of all class
objects.
* If that weren??™t confusing enough, the Class object has class Class as well.
Ruby Foundations | 5
The class Class inherits from Module; every class is also a module. However, there is
an important distinction. Classes cannot be mixed in to other classes, and classes
cannot extend objects; only modules can.
Method Lookup
Method lookup in Ruby can be very confusing, but it is quite regular. The easiest
way to understand complicated situations is to visualize the data structures that
Ruby creates behind the scenes.
Every Ruby object* has a set of fields in memory:
klass
A pointer to the class object of this object. (It is klass instead of class because
the latter is a reserved word in C++ and Ruby; if it were called class, Ruby
would compile with a C compiler but not with a C++ compiler.


Pages:
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30