<ppdoc>
<copyright>
    Copyright (c) 2001 by Addison Wesley Longman.  This
    material may be distributed only subject to the terms and
    conditions set forth in the Open Publication License, v1.0 or
    later (the latest version is presently available at
    http://www.opencontent.org/openpub/).
</copyright>
<chapter  ref="xref-000001" name="Classes and Objects">
<p/>
Classes and objects are obviously central to Ruby, but at first sight
they can seem a little confusing. There seem to be a lot of concepts:
classes, objects, class objects, instance methods, class methods, and
singleton classes. In reality, however, Ruby has just a single
underlying class and object structure, which we'll discuss in this
chapter. In fact, the basic model is so simple, we can describe it in
a single paragraph.
<p/>
A Ruby object has three components: a set of flags,
some instance variables, and an associated class. A Ruby class is an
object of class <classname>Class</classname>, which contains all the object things plus a
list of methods and a reference to a superclass (which is itself
another class). All method calls in Ruby nominate a receiver (which is
by default <var>self</var>, the current object).
Ruby finds the method to
invoke by looking at the list of methods in the receiver's class. If
it doesn't find the method there, it looks in the superclass, and then 
in the superclass's
superclass, and so on. If the method cannot be found in the receiver's
class or any of its ancestors, Ruby invokes the method
<meth>method_missing</meth> on the original receiver.
<p/>
And that's it---the entire explanation. On to the next chapter.
<p/>
``But wait,'' you cry, ``I spent good money on this chapter. What
about all this other stuff---singleton classes, class methods, and so
on. How do they work?''
<p/>
Good question.
<section>How Classes and Objects Interact</section>
<p/>
All class/object interactions are explained using the simple model
given above: objects reference classes, and
classes reference zero or more superclasses. However, the
implementation details can get a tad tricky.
<p/>
We've found that the simplest way of visualizing all this is to draw
the actual objects that Ruby implements. So, in the following pages
we'll look at all the possible combinations of classes and
objects. Note that these are not class diagrams in the UML sense;
we're showing structures in memory and pointers between them.
<subsection>Your Basic, Everyday Object</subsection>
<p/>
Let's start by looking at an object created from a simple
class. Figure 19.1 on page 239 shows
an object referenced by a variable, <tt>lucille</tt>, the object's class,
<classname>Guitar</classname>, and that class's superclass, <classname>Object</classname>. Notice how the
object's class reference (called <tt>klass</tt> for historical reasons
that really bug Andy) points to the class object, and how the
<tt>super</tt> pointer from that class references the parent class.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
When Ruby executes <tt>Guitar.strings()</tt>, it follows the same process
as before: it goes to the receiver, class <classname>Guitar</classname>, follows the
<tt>klass</tt> reference to class <classname>Guitar$'$</classname>, and finds the method.
<p/>
Finally, note that an ``S'' has crept into the flags in class
<classname>Guitar$'$</classname>. The classes that Ruby creates automatically are
marked internally as <em>singleton classes</em>.
Singleton classes are
treated slightly differently within Ruby. The most obvious difference
from the outside is that they are effectively invisible: they will
never appear in a list of objects returned from methods such as
<cim><file>module</file><front>Module</front><back>ancestors</back><mref>ancestors</mref></cim> or <mmm><file>objectspace</file><front>ObjectSpace</front><back>each_object</back><mref>each_object</mref></mmm>.
<subsection>Object-Specific Classes</subsection>
<p/>
Ruby allows you to create a class tied to a particular object. In the
following example, we create two <classname>String</classname> objects. We then associate 
an anonymous class with one of them,
overriding one of the methods in
the object's base class and adding a new method.
<p/>
<codefragment>
<fullcode><![CDATA[  a = "hello"
  b = a.dup
  
  class <<a
    def to_s
      "The value is '#{self}'"
    end
    def twoTimes
      self + self
    end
  end
  
  a.to_s
  a.twoTimes
  b.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>"hello"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b<nbsp/>=<nbsp/>a.dup</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>class<nbsp/>&lt;&lt;a</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"The<nbsp/>value<nbsp/>is<nbsp/>'#{self}'"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>twoTimes</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>self<nbsp/>+<nbsp/>self</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>a.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"The<nbsp/>value<nbsp/>is<nbsp/>'hello'"</tt></td>
</tr>
<tr>
  <td><tt>a.twoTimes</tt></td>
  <td>&#187;</td>
  <td><tt>"hellohello"</tt></td>
</tr>
<tr>
  <td><tt>b.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"hello"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This example uses the ``<tt>class &lt;&lt;</tt><obj>obj</obj>'' notation, which
basically says ``build me a new class just for object <obj>obj</obj>.'' We
could also have written it as:
<p/>
<codefragment>
<fullcode><![CDATA[  a = "hello"
  b = a.dup
  def a.to_s
    "The value is '#{self}'"
  end
  def a.twoTimes
    self + self
  end
  
  a.to_s
  a.twoTimes
  b.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>"hello"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b<nbsp/>=<nbsp/>a.dup</tt></td>
</tr>
<tr>
<td colspan="3"><tt>def<nbsp/>a.to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"The<nbsp/>value<nbsp/>is<nbsp/>'#{self}'"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>def<nbsp/>a.twoTimes</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>self<nbsp/>+<nbsp/>self</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>a.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"The<nbsp/>value<nbsp/>is<nbsp/>'hello'"</tt></td>
</tr>
<tr>
  <td><tt>a.twoTimes</tt></td>
  <td>&#187;</td>
  <td><tt>"hellohello"</tt></td>
</tr>
<tr>
  <td><tt>b.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"hello"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The effect is the same in both cases: a class is added to the object
``<tt>a</tt>''. This gives us a strong hint about the Ruby implementation: 
a singleton class is created and inserted as <tt>a</tt>'s direct
class. <tt>a</tt>'s original class, <classname>String</classname>, is made this singleton's
superclass. The before and after pictures are shown in Figure
19.3 on page 242.
<p/>
Ruby performs a slight optimization with these singleton classes. If
an object's <tt>klass</tt> reference already points to a singleton class,
a new one will not be created. This means that the first of the two
method definitions in the previous example will create a singleton
class, but the second will simply add a method to it.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
<subsection>Mixin Modules</subsection>
<p/>
When a class includes a module, that module's instance methods become
available as instance methods of the class. It's almost as if the
module becomes a superclass of the class that uses it. Not
surprisingly, that's about how it works. When you include a module,
Ruby creates an anonymous proxy class that references that module, and 
inserts that proxy as the direct superclass of the class that did the 
including. The proxy class contains references to the instance
variables and methods of the module. This is important: the same
module may be included in many different classes, and will appear in
many different inheritance chains. However, thanks to the proxy
class,
there is still only one underlying module: change a method definition
in that module, and it will change in all classes that include that
module, both past and future.
<p/>
<codefragment>
<fullcode><![CDATA[  module SillyModule
    def hello
      "Hello."
    end
  end
  class SillyClass
    include SillyModule
  end
  s = SillyClass.new
  s.hello
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>module<nbsp/>SillyModule</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>hello</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"Hello."</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>class<nbsp/>SillyClass</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>SillyModule</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>s<nbsp/>=<nbsp/>SillyClass.new</tt></td>
</tr>
<tr>
  <td><tt>s.hello</tt></td>
  <td>&#187;</td>
  <td><tt>"Hello."</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
<codefragment>
<fullcode><![CDATA[!-  module SillyModule
!-    def hello
!-      "Hello."
!-    end
!-  end
!-  class SillyClass
!-    include SillyModule
!-  end
!-  s = SillyClass.new
  module SillyModule
    def hello
      "Hi, there!"
    end
  end
  s.hello
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>module<nbsp/>SillyModule</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>hello</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"Hi,<nbsp/>there!"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>s.hello</tt></td>
  <td>&#187;</td>
  <td><tt>"Hi,<nbsp/>there!"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The relationship between classes and the modules they include is shown 
in Figure 19.4 on page 243. If multiple modules are included, they
are added to the chain in order.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
If a module itself includes other modules, a chain of proxy classes
will be added to any class that includes that module, one proxy for
each module that is directly or indirectly included.
<subsection>Extending Objects</subsection>
<p/>
Just as you can define an anonymous class for an 
object using ``<tt>class<nbsp/>&lt;&lt;<obj>obj</obj></tt>'', you can mix a module into an
object using <cim><file>object</file><front>Object</front><back>extend</back><mref>extend</mref></cim>. For example:
<p/>
<codefragment>
<fullcode><![CDATA[  module Humor
    def tickle
      "hee, hee!"
    end
  end

  a = "Grouchy"
  a.extend Humor   #!sh!
  a.tickle
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>module<nbsp/>Humor</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>tickle</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"hee,<nbsp/>hee!"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>"Grouchy"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a.extend<nbsp/>Humor</tt></td>
</tr>
<tr>
  <td><tt>a.tickle</tt></td>
  <td>&#187;</td>
  <td><tt>"hee,<nbsp/>hee!"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
There is an interesting trick with <meth>extend</meth>.
If you use it
within a class definition, the module's methods become class
methods.
<p/>
<codefragment>
<fullcode><![CDATA[  module Humor
    def tickle
      "hee, hee!"
    end
  end

  class Grouchy
    include Humor
    extend  Humor
  end

  Grouchy.tickle
  a = Grouchy.new
  a.tickle
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>module<nbsp/>Humor</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>tickle</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"hee,<nbsp/>hee!"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>class<nbsp/>Grouchy</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>Humor</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>extend<nbsp/><nbsp/>Humor</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>Grouchy.tickle</tt></td>
  <td>&#187;</td>
  <td><tt>"hee,<nbsp/>hee!"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>Grouchy.new</tt></td>
</tr>
<tr>
  <td><tt>a.tickle</tt></td>
  <td>&#187;</td>
  <td><tt>"hee,<nbsp/>hee!"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This is because calling <meth>extend</meth> is equivalent to
<tt>self.extend</tt>, so the methods are added to <tt>self</tt>, which in a
class definition is the class itself.
<section>Class and Module Definitions</section>
<p/>
Having exhausted the combinations of classes and objects, we can
(thankfully) get back to programming by looking at the nuts and bolts
of class and module definitions.
<p/>
In languages such as C++ and Java, class definitions are processed at
compile time: the compiler loads up symbol tables, works out how much
storage to allocate, constructs dispatch tables, and does all those other
obscure things we'd rather not think too hard about.
<p/>
Ruby is different. In Ruby, class and module definitions are executable
code. Although parsed at compile time, the classes and modules are
created at runtime, when the definition is encountered. (The same is
also true of method definitions.) This allows you to structure your
programs far more dynamically than in most conventional languages. 
You can make decisions once, when the class is being
defined, rather than each time that objects of the class are
used. The class in the following example decides as it is being
defined what version of a decryption routine to create.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  module Tracing
!-  end
!-  $DEBUGGING = true
!-  EXPORT_VERSION=true
  class MediaPlayer
    include Tracing if $DEBUGGING

    if ::EXPORT_VERSION
      def decrypt(stream)
        raise "Decryption not available"
      end
    else
      def decrypt(stream)
        # ...
      end
    end
    
  end
]]></fullcode>
class<nbsp/>MediaPlayer
<nbsp/><nbsp/>include<nbsp/>Tracing<nbsp/>if<nbsp/>$DEBUGGING
<p/>
<nbsp/><nbsp/>if<nbsp/>::EXPORT_VERSION
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>decrypt(stream)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>raise<nbsp/>"Decryption<nbsp/>not<nbsp/>available"
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>decrypt(stream)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
<p/>
end
</alltt>
</codefragment>
<p/>
If class definitions are executable code, this implies that they
execute in the context of some object: <var>self</var> must reference
<em>something</em>. Let's find out what it is.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Test
    puts "Type of self = #{self.type}"
    puts "Name of self = #{self.name}"
  end
]]></fullcode>
class<nbsp/>Test
<nbsp/><nbsp/>puts<nbsp/>"Type<nbsp/>of<nbsp/>self<nbsp/>=<nbsp/>#{self.type}"
<nbsp/><nbsp/>puts<nbsp/>"Name<nbsp/>of<nbsp/>self<nbsp/>=<nbsp/>#{self.name}"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Type<nbsp/>of<nbsp/>self<nbsp/>=<nbsp/>Class
Name<nbsp/>of<nbsp/>self<nbsp/>=<nbsp/>Test
</alltt>
</codefragment>
<p/>
This means that a class definition is executed with that class as the
current object. Referring back to the section about metaclasses
on page 238, we can see that this means that methods in
the metaclass and its superclasses will be available during the
execution of the method definition. We can check this out.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Test
    def Test.sayHello
      puts "Hello from #{name}"
    end

    sayHello
  end
]]></fullcode>
class<nbsp/>Test
<nbsp/><nbsp/>def<nbsp/>Test.sayHello
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Hello<nbsp/>from<nbsp/>#{name}"
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>sayHello
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Hello<nbsp/>from<nbsp/>Test
</alltt>
</codefragment>
<p/>
In this example we define a class method, <ccm><front>Test</front><back>sayHello</back></ccm>, and
then call it in the body of the class definition. Within
<tt>sayHello</tt>, we call <meth>name</meth>, an instance method of class
<classname>Module</classname>. Because <classname>Module</classname> is an ancestor of <classname>Class</classname>, its instance
methods can be called without an explicit receiver within a class definition.
<p/>
In fact, many of the directives that you use when defining a class
or module, things such as <meth>alias_method</meth>, <meth>attr</meth>, and
<meth>public</meth>, are simply methods in class <classname>Module</classname>. This opens up 
some interesting possibilities---you can extend the functionality of
class and module definitions by writing Ruby code. Let's look at a
couple of examples.
<p/>
As a first example, let's look at adding a basic documentation
facility to modules and classes.
This would allow us to associate a
string with modules and classes that we write, a string that is
accessible as the program is running. We'll choose a simple syntax.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Example
    doc "This is a sample documentation string"
    # .. rest of class
  end
]]></fullcode>
class<nbsp/>Example
<nbsp/><nbsp/>doc<nbsp/>"This<nbsp/>is<nbsp/>a<nbsp/>sample<nbsp/>documentation<nbsp/>string"
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>rest<nbsp/>of<nbsp/>class
end
</alltt>
</codefragment>
<p/>
We need to make <meth>doc</meth> available to any module or class, so we
need to make it an instance method of class <classname>Module</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Module
    @@docs = Hash.new(nil)
    def doc(str)
      @@docs[self.name] = str
    end
    
    def Module::doc(aClass)
      # If we're passed a class or module, convert to string
      # ('<=' for classes checks for same class or subtype)
      aClass = aClass.name if aClass.type <= Module
      @@docs[aClass] || "No documentation for #{aClass}"
    end
  end

  class Example
    doc "This is a sample documentation string"
    # .. rest of class
  end

  module Another
    doc <<-edoc
      And this is a documentation string
      in a module
    edoc
    # rest of module
  end

  puts Module::doc(Example)
  puts Module::doc("Another")
]]></fullcode>
class<nbsp/>Module
<nbsp/><nbsp/>@@docs<nbsp/>=<nbsp/>Hash.new(nil)
<nbsp/><nbsp/>def<nbsp/>doc(str)
<nbsp/><nbsp/><nbsp/><nbsp/>@@docs[self.name]<nbsp/>=<nbsp/>str
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>Module::doc(aClass)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>If<nbsp/>we're<nbsp/>passed<nbsp/>a<nbsp/>class<nbsp/>or<nbsp/>module,<nbsp/>convert<nbsp/>to<nbsp/>string
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>('&lt;='<nbsp/>for<nbsp/>classes<nbsp/>checks<nbsp/>for<nbsp/>same<nbsp/>class<nbsp/>or<nbsp/>subtype)
<nbsp/><nbsp/><nbsp/><nbsp/>aClass<nbsp/>=<nbsp/>aClass.name<nbsp/>if<nbsp/>aClass.type<nbsp/>&lt;=<nbsp/>Module
<nbsp/><nbsp/><nbsp/><nbsp/>@@docs[aClass]<nbsp/>||<nbsp/>"No<nbsp/>documentation<nbsp/>for<nbsp/>#{aClass}"
<nbsp/><nbsp/>end
end
<p/>
class<nbsp/>Example
<nbsp/><nbsp/>doc<nbsp/>"This<nbsp/>is<nbsp/>a<nbsp/>sample<nbsp/>documentation<nbsp/>string"
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>rest<nbsp/>of<nbsp/>class
end
<p/>
module<nbsp/>Another
<nbsp/><nbsp/>doc<nbsp/>&lt;&lt;-edoc
<nbsp/><nbsp/><nbsp/><nbsp/>And<nbsp/>this<nbsp/>is<nbsp/>a<nbsp/>documentation<nbsp/>string
<nbsp/><nbsp/><nbsp/><nbsp/>in<nbsp/>a<nbsp/>module
<nbsp/><nbsp/>edoc
<nbsp/><nbsp/>#<nbsp/>rest<nbsp/>of<nbsp/>module
end
<p/>
puts<nbsp/>Module::doc(Example)
puts<nbsp/>Module::doc("Another")
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>a<nbsp/>sample<nbsp/>documentation<nbsp/>string
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>And<nbsp/>this<nbsp/>is<nbsp/>a<nbsp/>documentation<nbsp/>string
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>in<nbsp/>a<nbsp/>module
</alltt>
</codefragment>
<p/>
The second example is a performance enhancement based on Tadayoshi Funaba's
<tt>date</tt> module
(described beginning on page 439). Say we
have a class that represents some underlying quantity (in this case, a
date).  The class may have many attributes that present the same
underlying date in different ways: as a Julian day number, as a
string, as a [year, month, day] triple, and so on. Each value
represents the same date and may involve a fairly complex calculation
to derive. We therefore would like to calculate each attribute only
once, when it is first accessed.
<p/>
The manual way would be to add a test to each accessor:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class ExampleDate
    def initialize(dayNumber)
      @dayNumber = dayNumber
    end
    
    def asDayNumber
      @dayNumber
    end
    
    def asString
      unless @string
        # complex calculation
        @string = result
      end
      @string
    end
    
    def asYMD
      unless @ymd
        # another calculation
        @ymd = [ y, m, d ]
      end
      @ymd
    end
    # ...
  end
]]></fullcode>
class<nbsp/>ExampleDate
<nbsp/><nbsp/>def<nbsp/>initialize(dayNumber)
<nbsp/><nbsp/><nbsp/><nbsp/>@dayNumber<nbsp/>=<nbsp/>dayNumber
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>asDayNumber
<nbsp/><nbsp/><nbsp/><nbsp/>@dayNumber
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>asString
<nbsp/><nbsp/><nbsp/><nbsp/>unless<nbsp/>@string
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>complex<nbsp/>calculation
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@string<nbsp/>=<nbsp/>result
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>@string
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>asYMD
<nbsp/><nbsp/><nbsp/><nbsp/>unless<nbsp/>@ymd
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>another<nbsp/>calculation
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@ymd<nbsp/>=<nbsp/>[<nbsp/>y,<nbsp/>m,<nbsp/>d<nbsp/>]
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>@ymd
<nbsp/><nbsp/>end
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
This is a clunky technique---let's see if we can come up with
something sexier.
<p/>
What we're aiming for is a directive that indicates that the body of a
particular method should be invoked only once. The value returned by
that first call should be cached. Thereafter, calling that same method
should return the cached value without reevaluating the method body
again. This is similar to Eiffel's <tt>once</tt> modifier for routines.
We'd like to be able to write something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class ExampleDate
!-  def ExampleDate.once(*a)
!-  end
    def asDayNumber
      @dayNumber
    end
    
    def asString
      # complex calculation
    end
    
    def asYMD
      # another calculation
      [ y, m, d ]
    end

    once :asString, :asYMD
  end
]]></fullcode>
class<nbsp/>ExampleDate
<nbsp/><nbsp/>def<nbsp/>asDayNumber
<nbsp/><nbsp/><nbsp/><nbsp/>@dayNumber
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>asString
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>complex<nbsp/>calculation
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>asYMD
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>another<nbsp/>calculation
<nbsp/><nbsp/><nbsp/><nbsp/>[<nbsp/>y,<nbsp/>m,<nbsp/>d<nbsp/>]
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>once<nbsp/>:asString,<nbsp/>:asYMD
end
</alltt>
</codefragment>
<p/>
We can use <tt>once</tt> as a directive by writing it as a class method of
<classname>ExampleDate</classname>,
but what should it look like internally?  The trick
is to have it rewrite the methods whose names it is passed. For each
method, it creates an alias for the original code, then creates a new
method with the same name. This new method does two things. First, it
invokes the original method (using the alias) and stores the resulting
value in an instance variable. Second, it redefines itself, so that on 
subsequent calls it simply returns the value of the instance variable
directly. Here's  Tadayoshi Funaba's code, slightly reformatted.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class ExampleDate
  def ExampleDate.once(*ids)
    for id in ids
      module_eval <<-"end_eval"
        alias_method :__#{id.to_i}__, #{id.inspect}
        def #{id.id2name}(*args, &block)
          def self.#{id.id2name}(*args, &block)
            @__#{id.to_i}__
          end
          @__#{id.to_i}__ = __#{id.to_i}__(*args, &block)
        end
      end_eval
    end
  end
!-end
]]></fullcode>
def<nbsp/>ExampleDate.once(*ids)
<nbsp/><nbsp/>for<nbsp/>id<nbsp/>in<nbsp/>ids
<nbsp/><nbsp/><nbsp/><nbsp/>module_eval<nbsp/>&lt;&lt;-"end_eval"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>alias_method<nbsp/>:__#{id.to_i}__,<nbsp/>#{id.inspect}
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>#{id.id2name}(*args,<nbsp/>&amp;block)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>self.#{id.id2name}(*args,<nbsp/>&amp;block)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@__#{id.to_i}__
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@__#{id.to_i}__<nbsp/>=<nbsp/>__#{id.to_i}__(*args,<nbsp/>&amp;block)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>end_eval
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This code uses <tt>module_eval</tt> to execute a block of code in the context of
the calling module (or, in this case, the calling class). The original
method is renamed <em>__nnn__</em>, where the <em>nnn</em> part is
the integer representation of the method name's symbol id. The code
uses the same name for the caching instance variable. The bulk
of the code is a method that dynamically redefines itself. Note that
this redefinition uses the fact that methods may contain nested
singleton method definitions, a clever trick.
<p/>
Understand this code, and you'll be well on the way to true Ruby mastery.
<p/>
However, we can take it further. Look in the <meth>date</meth> module, and you'll
see method <tt>once</tt> written slightly differently.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Date
  class << self
    def once(*ids)
      # ...
    end
  end
  # ...
end
]]></fullcode>
class<nbsp/>Date
<nbsp/><nbsp/>class<nbsp/>&lt;&lt;<nbsp/>self
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>once(*ids)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
The interesting thing here is the inner class definition,
``<tt>class<nbsp/>&lt;&lt;<nbsp/>self</tt>''. This defines a class based on the object
<const>self</const>, and <const>self</const> happens to be the class object for
<classname>Date</classname>. The result? Every method within the inner class definition
is automatically a class method of <classname>Date</classname>.
<p/>
The <meth>once</meth> feature is generally
applicable---it should work for any class. If you took <meth>once</meth>
and made it a private instance method of class <classname>Module</classname>, it would be
available for use in any Ruby class.
<subsection>Class Names Are Constants</subsection>
<p/>
We've said that when you invoke a class method, all you're doing is
sending a message to the <classname>Class</classname> object itself. When you say
something such as <tt>String.new("gumby")</tt>, you're sending the message 
<meth>new</meth> to the object that is class <classname>String</classname>. But how does Ruby 
know to do this? After all, the receiver of a message should be an
object reference, which implies that there must be a 
constant called ``String'' somewhere containing a reference to the
<classname>String</classname> object.<footnote>It will be a constant, not a variable,
  because ``String'' starts with an uppercase letter.</footnote>
And in fact, that's exactly what happens. All the built-in classes,
along with the classes you define, have a corresponding global
constant with the same name as the class.
This is both straightforward and subtle. The subtlety comes from the
fact that there are actually two things named (for example) <classname>String</classname> in the
system. There's a <em>constant</em> that references an object of class
<classname>String</classname>, and there's the object itself.
<p/>
The fact that class names are just constants means that you can treat
classes just like any other Ruby object: you can copy them, pass them
to methods, and use them in expressions.
<p/>
<codefragment>
<fullcode><![CDATA[  def factory(klass, *args)
    klass.new(*args)
  end

  factory(String, "Hello")
  factory(Dir,    ".")

  flag = true
  (flag ? Array : Hash)[1, 2, 3, 4]
  flag = false
  (flag ? Array : Hash)[1, 2, 3, 4]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>factory(klass,<nbsp/>*args)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>klass.new(*args)</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>factory(String,<nbsp/>"Hello")</tt></td>
  <td>&#187;</td>
  <td><tt>"Hello"</tt></td>
</tr>
<tr>
  <td><tt>factory(Dir,<nbsp/><nbsp/><nbsp/><nbsp/>".")</tt></td>
  <td>&#187;</td>
  <td><tt>#&lt;Dir:0x401b3234&gt;</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>flag<nbsp/>=<nbsp/>true</tt></td>
</tr>
<tr>
  <td><tt>(flag<nbsp/>?<nbsp/>Array<nbsp/>:<nbsp/>Hash)[1,<nbsp/>2,<nbsp/>3,<nbsp/>4]</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>2,<nbsp/>3,<nbsp/>4]</tt></td>
</tr>
<tr>
<td colspan="3"><tt>flag<nbsp/>=<nbsp/>false</tt></td>
</tr>
<tr>
  <td><tt>(flag<nbsp/>?<nbsp/>Array<nbsp/>:<nbsp/>Hash)[1,<nbsp/>2,<nbsp/>3,<nbsp/>4]</tt></td>
  <td>&#187;</td>
  <td><tt>{1=&gt;2,<nbsp/>3=&gt;4}</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Top-Level Execution Environment</section>
<p/>
Many times in this book we've claimed that everything in Ruby is an
object. However, there's one thing that we've used time and time again 
that appears to contradict this---the top-level Ruby execution environment.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  puts "Hello, World"
]]></fullcode>
puts<nbsp/>"Hello,<nbsp/>World"
</alltt>
</codefragment>
<p/>
Not an object in sight. We may as well be writing some variant of
Fortran or QW-Basic.  But dig deeper, and you'll come across objects
and classes lurking in even the simplest code.
<p/>
We know that the literal <tt>"Hello, World"</tt> generates a Ruby
<classname>String</classname>, so there's one object. We also know that the bare method
call to <meth>puts</meth> is effectively the same as <tt>self.puts</tt>. But
what is ``self''?
<p/>
<codefragment>
<fullcode><![CDATA[  self.type
]]></fullcode><rubycode>
<tr>
  <td><tt>self.type</tt></td>
  <td>&#187;</td>
  <td><tt>Object</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
At the top level, we're executing code in the context of some
predefined object. When we define methods, we're actually creating
(private) singleton methods for this object. Instance variables belong
to this object. And because we're in the context of <classname>Object</classname>, we can 
use all of <classname>Object</classname>'s methods (including those mixed-in from <modulename>Kernel</modulename>) 
in function form. This explains why we can call <modulename>Kernel</modulename> methods
such as <meth>puts</meth> at the top level (and indeed throughout Ruby):
these methods are part of every object.
<section>Inheritance and Visibility</section>
<p/>
There's one last wrinkle to class inheritance, and it's fairly
obscure.
<p/>
Within a class definition, you can change the visibility of a method
in an ancestor class. For example, you can do something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Base
  def aMethod
    puts "Got here"
  end
  private :aMethod
end

class Derived1 < Base
  public :aMethod
end

class Derived2 < Base
end
]]></fullcode>
class<nbsp/>Base
<nbsp/><nbsp/>def<nbsp/>aMethod
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Got<nbsp/>here"
<nbsp/><nbsp/>end
<nbsp/><nbsp/>private<nbsp/>:aMethod
end
<p/>
class<nbsp/>Derived1<nbsp/>&lt;<nbsp/>Base
<nbsp/><nbsp/>public<nbsp/>:aMethod
end
<p/>
class<nbsp/>Derived2<nbsp/>&lt;<nbsp/>Base
end
</alltt>
</codefragment>
<p/>
In this example, you would be able to invoke <meth>aMethod</meth> in
instances of class <classname>Derived1</classname>, but not via instances of <classname>Base</classname> or
<classname>Derived2</classname>.
<p/>
So how does Ruby pull off this feat of having one method 
with two different visibilities? Simply put, it cheats.
<p/>
If a subclass changes the visibility of a method in a parent, Ruby
effectively inserts a hidden proxy method in the subclass that invokes 
the original method using <kw>super</kw>. It then sets the visibility
of that proxy to whatever you requested. This means that the code:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Base
!-  def aMethod
!-    puts "Got here"
!-  end
!-  private :aMethod
!-end
class Derived1 < Base
  public :aMethod
end
]]></fullcode>
class<nbsp/>Derived1<nbsp/>&lt;<nbsp/>Base
<nbsp/><nbsp/>public<nbsp/>:aMethod
end
</alltt>
</codefragment>
<p/>
is effectively the same as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Base
!-  def aMethod
!-    puts "Got here"
!-  end
!-  private :aMethod
!-end
class Derived1 < Base
  def aMethod(*args)
    super
  end
  public :aMethod
end
]]></fullcode>
class<nbsp/>Derived1<nbsp/>&lt;<nbsp/>Base
<nbsp/><nbsp/>def<nbsp/>aMethod(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>super
<nbsp/><nbsp/>end
<nbsp/><nbsp/>public<nbsp/>:aMethod
end
</alltt>
</codefragment>
<p/>
The call to <kw>super</kw> can access the parent's method regardless of
its visibility, so the rewrite allows the subclass to override its
parent's visibility rules. Pretty scary, eh?
<section>Freezing Objects</section>
<p/>
There are times when you've worked hard to make your object exactly
right, and you'll be damned if you'll let anyone just change
it. Perhaps you need to pass some kind of opaque object between two of 
your classes via some third-party object, and you want to make sure it 
arrives unmodified. Perhaps you want to use an object as a hash key, and
need to make sure that no one modifies it while it's being used.
Perhaps something is corrupting one of your objects, and you'd like
Ruby to raise an exception as soon as the change occurs. 
<p/>
Ruby provides a very simple mechanism to help with this. Any object can be
<em>frozen</em> by invoking <cim><file>object</file><front>Object</front><back>freeze</back><mref>freeze</mref></cim>. A frozen object may
not be modified: you can't change its instance variables (directly or
indirectly), you can't associate singleton methods with it, and, if it 
is a class or module, you can't add, delete, or modify its
methods. Once frozen, an object stays frozen: there is no
<cim><file>object</file><front>Object</front><back>thaw</back><mref>thaw</mref></cim>. You can test to see if an object is frozen using
<cim><file>object</file><front>Object</front><back>frozen?</back><mref>frozen_qm</mref></cim>.
<p/>
What happens when you copy a frozen object? That depends on the method 
you use. If you call an object's <meth>clone</meth> method, the entire
object state (including whether it is frozen) is copied to the new
object. On the other hand, <meth>dup</meth> typically copies only the
object's contents---the new copy will not inherit the frozen status.
<p/>
<codefragment>
<fullcode><![CDATA[  str1 = "hello"
  str1.freeze
  str1.frozen?
  str2 = str1.clone
  str2.frozen?
  str3 = str1.dup
  str3.frozen?
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>str1<nbsp/>=<nbsp/>"hello"</tt></td>
</tr>
<tr>
  <td><tt>str1.freeze</tt></td>
  <td>&#187;</td>
  <td><tt>"hello"</tt></td>
</tr>
<tr>
  <td><tt>str1.frozen?</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
<td colspan="3"><tt>str2<nbsp/>=<nbsp/>str1.clone</tt></td>
</tr>
<tr>
  <td><tt>str2.frozen?</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
<td colspan="3"><tt>str3<nbsp/>=<nbsp/>str1.dup</tt></td>
</tr>
<tr>
  <td><tt>str3.frozen?</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Although freezing objects may initially seem like a good idea, you
might want to hold off doing it until you come across a real
need. Freezing is one of those ideas that looks essential on paper but 
isn't used much in practice.
</chapter>
</ppdoc>
