Prev | Current Page 27 | Next

Brad Ediger

"Advanced Rails"

In our code, we can assume that the singleton class exists; in reality, for
efficiency, Ruby creates it only when we first mention it.
Ruby allows singleton classes to be defined on any object except Fixnums or symbols.
Fixnums and symbols are immediate values (for efficiency, they??™re stored as themselves in
memory, rather than as a pointer to a data structure). Because they??™re stored on their
own, they don??™t have klass pointers, so there??™s no way to alter their method lookup
chain.
You can open singleton classes for true, false, and nil, but the singleton class
returned will be the same as the object??™s class. These values are singleton instances
(the only instances) of TrueClass, FalseClass, and NilClass, respectively. When you
ask for the singleton class of true, you will get TrueClass, as the immediate value
true is the only possible instance of that class. In Ruby:
true.class # => TrueClass
class << true; self; end # => TrueClass
true.class == (class << true; self; end) # => true
Singleton classes of class objects
Here is where it gets complicated. Keep in mind the basic rule of method lookup:
first Ruby follows an object??™s klass pointer and searches for methods; then Ruby
keeps following super pointers all the way up the chain until it finds the appropriate
method or reaches the top.
The important thing to remember is that classes are objects, too.


Pages:
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39