<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman, Inc. 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/).
<p/>
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
<p/>
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.
</copyright>
<chapter  ref="xref-000001" name="Reflection, ObjectSpace, and Distributed  Ruby">
<p/>
One of the many advantages of dynamic languages such as Ruby is the
ability to <em>introspect</em>---to examine aspects of the program from
within the program itself.  Java, for one, calls this
feature <em>reflection</em>.
<p/>
The word ``reflection''
conjures up an image of looking at oneself in the mirror---perhaps
investigating the relentless spread of that bald spot on the top of
one's head.  That's a pretty apt analogy: we use reflection to examine
parts of our programs that aren't normally visible from where we stand.
<p/>
In this deeply introspective mood, while we are contemplating our
navels and burning incense (being careful not to swap the two tasks),
what can we learn about our program? We might discover:
<p/>
<ul>
  <li> what objects it contains,
  </li><li> the current class hierarchy,
  </li><li> the contents and behaviors of objects, and
  </li><li> information on methods.
</li></ul>
<p/>
Armed with this information, we can look at particular objects
and decide which of their methods to call at runtime---even if the class of
the object didn't exist when we first wrote the code. We can also
start doing clever things, perhaps modifying the program as it's
running.
<p/>
Sound scary? It needn't be. In fact, these reflection capabilities let
us do some very useful things. Later in this chapter we'll look at
distributed Ruby and marshaling, two reflection-based technologies
that let us send objects around the world and through time.
<section>Looking at Objects</section>
<p/>
Have you ever craved the ability to traverse <em>all</em> the living objects
in your program?  We have!  Ruby lets you perform
this trick with <mmm><file>objectspace</file><front>ObjectSpace</front><back>each_object</back><mref>each_object</mref></mmm>.  We can use it to
do all sorts of neat tricks.
<p/>
For example, to iterate over all objects of type <classname>Numeric</classname>, you'd
write the following.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a = 102.7
  b = 95.1
  ObjectSpace.each_object(Numeric) {|x| p x }
]]></fullcode>
a<nbsp/>=<nbsp/>102.7
b<nbsp/>=<nbsp/>95.1
ObjectSpace.each_object(Numeric)<nbsp/>{|x|<nbsp/>p<nbsp/>x<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
95.1
102.7
2.718281828
3.141592654
</alltt>
</codefragment>
<p/>
Hey, where did those last two numbers come from?  We didn't define
them in our program.  If you look on page 429, you'll 
see that the <modulename>Math</modulename> module defines constants for e and PI; since we are
examining <em>all</em> living objects in the system, these turn up as
well.
<p/>
However, there is a catch. Let's try the same example with different
numbers.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a = 102
  b = 95
  ObjectSpace.each_object(Numeric) {|x| p x }
]]></fullcode>
a<nbsp/>=<nbsp/>102
b<nbsp/>=<nbsp/>95
ObjectSpace.each_object(Numeric)<nbsp/>{|x|<nbsp/>p<nbsp/>x<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
2.718281828
3.141592654
</alltt>
</codefragment>
<p/>
Neither of the <classname>Fixnum</classname> objects we created showed up. That's because 
<modulename>ObjectSpace</modulename> doesn't know about objects with immediate values:
<classname>Fixnum</classname>, <const>true</const>, <const>false</const>, and <tt>nil</tt>.
<subsection>Looking Inside Objects</subsection>
<p/>
Once you've found an interesting object, you may be tempted to find
out just what it can do. Unlike static languages, where a variable's
type determines its class, and hence the methods it supports, Ruby
supports liberated objects. You really cannot tell exactly what an
object can do until you look under its hood.<footnote>Or under its bonnet, for
  objects created to the east of the Atlantic.</footnote>
<p/>
For instance, we can get a list of all the methods to which an object will 
respond.
<p/>
<codefragment>
<fullcode><![CDATA[  r = 1..10 # Create a Range object
  list = r.methods
  list.length
  list[0..3]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>r<nbsp/>=<nbsp/>1..10<nbsp/>#<nbsp/>Create<nbsp/>a<nbsp/>Range<nbsp/>object</tt></td>
</tr>
<tr>
<td colspan="3"><tt>list<nbsp/>=<nbsp/>r.methods</tt></td>
</tr>
<tr>
  <td><tt>list.length</tt></td>
  <td>&#187;</td>
  <td><tt>60</tt></td>
</tr>
<tr>
  <td><tt>list[0..3]</tt></td>
  <td>&#187;</td>
  <td><tt>["size",<nbsp/>"end",<nbsp/>"length",<nbsp/>"exclude_end?"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Or, we can check to see if an object supports a particular method.
<p/>
<codefragment>
<fullcode><![CDATA[!- r = 1..10 # Create a Range object
  r.respond_to?("frozen?")
  r.respond_to?("hasKey")
  "me".respond_to?("==")
]]></fullcode><rubycode>
<tr>
  <td><tt>r.respond_to?("frozen?")</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>r.respond_to?("hasKey")</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
<tr>
  <td><tt>"me".respond_to?("==")</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
We can determine our object's class and its unique object id, and test
its relationship to other classes.
<p/>
<codefragment>
<fullcode><![CDATA[  num = 1
  num.id
  num.class
  num.kind_of? Fixnum
  num.kind_of? Numeric
  num.instance_of? Fixnum
  num.instance_of? Numeric
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>num<nbsp/>=<nbsp/>1</tt></td>
</tr>
<tr>
  <td><tt>num.id</tt></td>
  <td>&#187;</td>
  <td><tt>3</tt></td>
</tr>
<tr>
  <td><tt>num.class</tt></td>
  <td>&#187;</td>
  <td><tt>Fixnum</tt></td>
</tr>
<tr>
  <td><tt>num.kind_of?<nbsp/>Fixnum</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>num.kind_of?<nbsp/>Numeric</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>num.instance_of?<nbsp/>Fixnum</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>num.instance_of?<nbsp/>Numeric</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Looking at Classes</section>
<p/>
Knowing about objects is one part of reflection, but to get the whole
picture, you also need to be able to look at classes---the methods
and constants that they contain.
<p/>
Looking at the class hierarchy is easy. You can get the parent of any
particular class using <cim><file>class</file><front>Class</front><back>superclass</back><mref>superclass</mref></cim>. For
classes <em>and</em> modules, <cim><file>module</file><front>Module</front><back>ancestors</back><mref>ancestors</mref></cim> lists both
superclasses and mixed-in modules.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  klass = Fixnum
  begin
    print klass
    klass = klass.superclass
    print " < " if klass
  end while klass
  puts
  p Fixnum.ancestors
]]></fullcode>
klass<nbsp/>=<nbsp/>Fixnum
begin
<nbsp/><nbsp/>print<nbsp/>klass
<nbsp/><nbsp/>klass<nbsp/>=<nbsp/>klass.superclass
<nbsp/><nbsp/>print<nbsp/>"<nbsp/>&lt;<nbsp/>"<nbsp/>if<nbsp/>klass
end<nbsp/>while<nbsp/>klass
puts
p<nbsp/>Fixnum.ancestors
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Fixnum<nbsp/>&lt;<nbsp/>Integer<nbsp/>&lt;<nbsp/>Numeric<nbsp/>&lt;<nbsp/>Object
[Fixnum,<nbsp/>Integer,<nbsp/>Precision,<nbsp/>Numeric,<nbsp/>Comparable,<nbsp/>Object,<nbsp/>Kernel]
</alltt>
</codefragment>
<p/>
If you want to build a complete class hierarchy, just run that code
for every class in the system.  We can use <modulename>ObjectSpace</modulename> to iterate
over all <classname>Class</classname> objects:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  ObjectSpace.each_object(Class) do |aClass|
     # ...
  end
]]></fullcode>
ObjectSpace.each_object(Class)<nbsp/>do<nbsp/>|aClass|
<nbsp/><nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<subsection>Looking Inside Classes</subsection>
<p/>
We can find out a bit more about the methods and constants in a
particular object.  Instead of just checking to see whether the object 
responds to a given message, we can ask for methods by access level,
we can ask for just singleton methods, and we can have a look at
the object's constants.
<p/>
<codefragment>
<fullcode><![CDATA[  class Demo
    private
      def privMethod
      end
    protected
      def protMethod
      end
    public
      def pubMethod
      end

    def Demo.classMethod
    end
    
    CONST = 1.23
  end

  Demo.private_instance_methods
  Demo.protected_instance_methods
  Demo.public_instance_methods
  Demo.singleton_methods
  Demo.constants - Demo.superclass.constants
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Demo</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>private</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>privMethod</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>protected</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>protMethod</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>public</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>pubMethod</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>Demo.classMethod</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>CONST<nbsp/>=<nbsp/>1.23</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>Demo.private_instance_methods</tt></td>
  <td>&#187;</td>
  <td><tt>["privMethod"]</tt></td>
</tr>
<tr>
  <td><tt>Demo.protected_instance_methods</tt></td>
  <td>&#187;</td>
  <td><tt>["protMethod"]</tt></td>
</tr>
<tr>
  <td><tt>Demo.public_instance_methods</tt></td>
  <td>&#187;</td>
  <td><tt>["pubMethod"]</tt></td>
</tr>
<tr>
  <td><tt>Demo.singleton_methods</tt></td>
  <td>&#187;</td>
  <td><tt>["classMethod"]</tt></td>
</tr>
<tr>
  <td><tt>Demo.constants<nbsp/>-<nbsp/>Demo.superclass.constants</tt></td>
  <td>&#187;</td>
  <td><tt>["CONST"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
<ccm><file>module</file><front>Module</front><back>constants</back><mref>constants</mref></ccm> returns
<em>all</em> the constants available via a module, including
constants from the module's superclasses. We're not interested in
those just at the moment, so we'll subtract them from our list.
<p/>
Given a list of method names, we might now be tempted to try calling them.
Fortunately, that's easy with Ruby.
<section>Calling Methods Dynamically</section>
<p/>
C and Java programmers often find themselves writing some kind of
dispatch table: functions which are invoked based on a command.  Think
of a typical C idiom where you have to translate a string to a
function pointer:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  typedef struct {
    char *name;
    void (*fptr)();
  } Tuple;

  Tuple list[]= {
    { "play",   fptr_play },
    { "stop",   fptr_stop },
    { "record", fptr_record },
    { 0, 0 },
  };

  ...

  void dispatch(char *cmd) {
    int i = 0;
    for (; list[i].name; i++) {
      if (strncmp(list[i].name,cmd,strlen(cmd)) == 0) {
        list[i].fptr();
        return;
      }
    }
    /* not found */
  }
]]></fullcode>
typedef<nbsp/>struct<nbsp/>{
<nbsp/><nbsp/>char<nbsp/>*name;
<nbsp/><nbsp/>void<nbsp/>(*fptr)();
}<nbsp/>Tuple;
<p/>
Tuple<nbsp/>list[]=<nbsp/>{
<nbsp/><nbsp/>{<nbsp/>"play",<nbsp/><nbsp/><nbsp/>fptr_play<nbsp/>},
<nbsp/><nbsp/>{<nbsp/>"stop",<nbsp/><nbsp/><nbsp/>fptr_stop<nbsp/>},
<nbsp/><nbsp/>{<nbsp/>"record",<nbsp/>fptr_record<nbsp/>},
<nbsp/><nbsp/>{<nbsp/>0,<nbsp/>0<nbsp/>},
};
<p/>
...
<p/>
void<nbsp/>dispatch(char<nbsp/>*cmd)<nbsp/>{
<nbsp/><nbsp/>int<nbsp/>i<nbsp/>=<nbsp/>0;
<nbsp/><nbsp/>for<nbsp/>(;<nbsp/>list[i].name;<nbsp/>i++)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(strncmp(list[i].name,cmd,strlen(cmd))<nbsp/>==<nbsp/>0)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>list[i].fptr();
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return;
<nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/>}
<nbsp/><nbsp/>/*<nbsp/>not<nbsp/>found<nbsp/>*/
}
</alltt>
</codefragment>
<p/>
In Ruby, you can do all this in one line.  Stick all your command
functions into a class, create an instance of that class (we called it 
<meth>commands</meth>), and ask that object to execute a method called the
same name as the command string.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  commands.send(commandString)
]]></fullcode>
commands.send(commandString)
</alltt>
</codefragment>
<p/>
Oh, and by the way, it does much more than the C version---it's
dynamic.  The Ruby version will find new methods added at runtime just
as easily.
<p/>
You don't have to write special command classes for <meth>send</meth>: it
works on any object.
<p/>
<codefragment>
<fullcode><![CDATA[  "John Coltrane".send(:length)
  "Miles Davis".send("sub", /iles/, '.')
]]></fullcode><rubycode>
<tr>
  <td><tt>"John<nbsp/>Coltrane".send(:length)</tt></td>
  <td>&#187;</td>
  <td><tt>13</tt></td>
</tr>
<tr>
  <td><tt>"Miles<nbsp/>Davis".send("sub",<nbsp/>/iles/,<nbsp/>'.')</tt></td>
  <td>&#187;</td>
  <td><tt>"M.<nbsp/>Davis"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Another way of invoking methods dynamically uses <classname>Method</classname> objects.  A
<classname>Method</classname> object is like a <classname>Proc</classname> object: it represents a chunk of
code and a context in which it executes. In this case, the code is the
body of the method, and the context is the object that created the
method. Once we have our <classname>Method</classname> object, we can execute it sometime
later by sending it the message <meth>call</meth>.
<p/>
<codefragment>
<fullcode><![CDATA[  trane = "John Coltrane".method(:length)
  miles = "Miles Davis".method("sub")

  trane.call
  miles.call(/iles/, '.')
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>trane<nbsp/>=<nbsp/>"John<nbsp/>Coltrane".method(:length)</tt></td>
</tr>
<tr>
<td colspan="3"><tt>miles<nbsp/>=<nbsp/>"Miles<nbsp/>Davis".method("sub")</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>trane.call</tt></td>
  <td>&#187;</td>
  <td><tt>13</tt></td>
</tr>
<tr>
  <td><tt>miles.call(/iles/,<nbsp/>'.')</tt></td>
  <td>&#187;</td>
  <td><tt>"M.<nbsp/>Davis"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can pass the <classname>Method</classname> object around as you would any other
object, and when you invoke <cim><file>method</file><front>Method</front><back>call</back><mref>call</mref></cim>, the method is run just
as if you had invoked it on the original object.  It's like having a
C-style function pointer but in a fully object-oriented style.
<p/>
You can also use <classname>Method</classname> objects with iterators.
<p/>
<codefragment>
<fullcode><![CDATA[  def double(a)
    2*a
  end

  mObj = method(:double)

  [ 1, 3, 5, 7 ].collect(&mObj)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>double(a)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>2*a</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>mObj<nbsp/>=<nbsp/>method(:double)</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7<nbsp/>].collect(&amp;mObj)</tt></td>
  <td>&#187;</td>
  <td><tt>[2,<nbsp/>6,<nbsp/>10,<nbsp/>14]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
As good things come in threes, here's yet another way to invoke
methods dynamically. The <tt>eval</tt>
method (and its variations such as
<tt>class_eval</tt>, <tt>module_eval</tt>, and <tt>instance_eval</tt>) will
parse and execute an arbitrary string of legal Ruby source code.
<p/>
<codefragment>
<fullcode><![CDATA[  trane = %q{"John Coltrane".length}
  miles = %q{"Miles Davis".sub(/iles/, '.')}

  eval trane
  eval miles
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>trane<nbsp/>=<nbsp/>%q{"John<nbsp/>Coltrane".length}</tt></td>
</tr>
<tr>
<td colspan="3"><tt>miles<nbsp/>=<nbsp/>%q{"Miles<nbsp/>Davis".sub(/iles/,<nbsp/>'.')}</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>eval<nbsp/>trane</tt></td>
  <td>&#187;</td>
  <td><tt>13</tt></td>
</tr>
<tr>
  <td><tt>eval<nbsp/>miles</tt></td>
  <td>&#187;</td>
  <td><tt>"M.<nbsp/>Davis"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
When using <tt>eval</tt>, it can be helpful to state explicitly the
context in which the expression should be evaluated, rather than using
the current context.  You can obtain a context by calling
<mim><file>kernel</file><front>Kernel</front><back>binding</back><mref>binding</mref></mim> at the desired point.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Cents
!-  def initialize(a)
!-    @amt = a
!-  end
!-  def to_s
!-    "$0." + @amt.to_s + "USD"
!-  end
!-end
  class CoinSlot
    def initialize(amt=Cents.new(25))
      @amt = amt
      $here = binding
    end
  end

  a = CoinSlot.new
  eval "puts @amt", $here
  eval "puts @amt"
]]></fullcode>
class<nbsp/>CoinSlot
<nbsp/><nbsp/>def<nbsp/>initialize(amt=Cents.new(25))
<nbsp/><nbsp/><nbsp/><nbsp/>@amt<nbsp/>=<nbsp/>amt
<nbsp/><nbsp/><nbsp/><nbsp/>$here<nbsp/>=<nbsp/>binding
<nbsp/><nbsp/>end
end
<p/>
a<nbsp/>=<nbsp/>CoinSlot.new
eval<nbsp/>"puts<nbsp/>@amt",<nbsp/>$here
eval<nbsp/>"puts<nbsp/>@amt"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
$0.25USD
nil
</alltt>
</codefragment>
<p/>
The first <tt>eval</tt> evaluates <tt>@amt</tt> in the context of the instance
of class <classname>CoinSlot</classname>.  The second <tt>eval</tt> evaluates <tt>@amt</tt> in
the context of <classname>Object</classname>, where the instance variable <tt>@amt</tt> is
not defined.
<subsection>Performance Considerations</subsection>
<p/>
As we've seen in this section, there are several ways to invoke an
arbitrary method of some object: <cim><file>object</file><front>Object</front><back>send</back><mref>send</mref></cim>, 
<cim><file>method</file><front>Method</front><back>call</back><mref>call</mref></cim>, and the various flavors of <meth>eval</meth>.
<p/>
You may prefer to use any one of these techniques depending on your
needs, but be aware that <tt>eval</tt> is significantly slower than the
others (or, for optimistic readers, <tt>send</tt> and <tt>call</tt> are
significantly faster than <tt>eval</tt>).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require "benchmark"   # from the Ruby Application Archive
  include Benchmark

  test = "Stormy Weather"
  m = test.method(:length)
  n = 100000

  bm(12) {|x|
    x.report("call") { n.times { m.call } }
    x.report("send") { n.times { test.send(:length) } }
    x.report("eval") { n.times { eval "test.length" } }
  }
]]></fullcode>
require<nbsp/>"benchmark"<nbsp/><nbsp/><nbsp/>#<nbsp/>from<nbsp/>the<nbsp/>Ruby<nbsp/>Application<nbsp/>Archive
include<nbsp/>Benchmark
<p/>
test<nbsp/>=<nbsp/>"Stormy<nbsp/>Weather"
m<nbsp/>=<nbsp/>test.method(:length)
n<nbsp/>=<nbsp/>100000
<p/>
bm(12)<nbsp/>{|x|
<nbsp/><nbsp/>x.report("call")<nbsp/>{<nbsp/>n.times<nbsp/>{<nbsp/>m.call<nbsp/>}<nbsp/>}
<nbsp/><nbsp/>x.report("send")<nbsp/>{<nbsp/>n.times<nbsp/>{<nbsp/>test.send(:length)<nbsp/>}<nbsp/>}
<nbsp/><nbsp/>x.report("eval")<nbsp/>{<nbsp/>n.times<nbsp/>{<nbsp/>eval<nbsp/>"test.length"<nbsp/>}<nbsp/>}
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>user<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>system<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>total<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>real
call<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>0.220000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.220000<nbsp/>(<nbsp/><nbsp/>0.214065)
send<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>0.210000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.210000<nbsp/>(<nbsp/><nbsp/>0.217070)
eval<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>2.540000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>2.540000<nbsp/>(<nbsp/><nbsp/>2.518311)
</alltt>
</codefragment>
<section>System Hooks</section>
<p/>
A <em>hook</em> is a technique that lets you trap some Ruby event, such
as object creation.
<p/>
The simplest hook technique in Ruby is to intercept calls to methods
in system classes. Perhaps you want to log all the operating system
commands your program executes. Simply rename the method
<mmm><file>kernel</file><front>Kernel</front><back>system</back><mref>system</mref></mmm><footnote>This Eiffel-inspired  
  idiom of renaming a
  feature and redefining a new one is very useful, but be aware that
  it can cause problems. If a subclass does the same thing, and
  renames the methods using the same names, you'll end up with an
  infinite loop. You can avoid this by aliasing your methods to a
  unique symbol name or by using a consistent naming convention.</footnote>
and substitute it with one of your own that both logs the command and
calls the original <modulename>Kernel</modulename> method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Kernel
    alias_method :old_system, :system
    def system(*args)
      result = old_system(*args)
      puts "system(#{args.join(', ')}) returned #{result}"
      result
    end
  end
  
  system("date")
  system("kangaroo", "-hop 10", "skippy")
]]></fullcode>
module<nbsp/>Kernel
<nbsp/><nbsp/>alias_method<nbsp/>:old_system,<nbsp/>:system
<nbsp/><nbsp/>def<nbsp/>system(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>old_system(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"system(#{args.join(',<nbsp/>')})<nbsp/>returned<nbsp/>#{result}"
<nbsp/><nbsp/><nbsp/><nbsp/>result
<nbsp/><nbsp/>end
end
<p/>
system("date")
system("kangaroo",<nbsp/>"-hop<nbsp/>10",<nbsp/>"skippy")
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Sun<nbsp/>Jun<nbsp/><nbsp/>9<nbsp/>00:09:44<nbsp/>CDT<nbsp/>2002
system(date)<nbsp/>returned<nbsp/>true
system(kangaroo,<nbsp/>-hop<nbsp/>10,<nbsp/>skippy)<nbsp/>returned<nbsp/>false
</alltt>
</codefragment>
<p/>
A more powerful hook is catching objects as they are created.
If you can be 
present when every object is born, you can do all sorts of interesting
things: you can wrap them, add methods to them, remove methods from them, add them
to containers to implement persistence, you name it. We'll show a
simple example here: we'll add a timestamp to every object as it's
created. 
<p/>
One way to hook object creation is to do our method renaming trick on
<cim><file>class</file><front>Class</front><back>new</back><mref>new</mref></cim>, the method that's called to allocate space for a new
object. The technique isn't perfect---some built-in objects, such as
literal strings, are constructed without calling <meth>new</meth>---but
it'll work just fine for objects we write.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class Object
!-    def timestamp
!-      return @timestamp
!-    end
!-    def timestamp=(aTime)
!-      @timestamp = aTime
!-    end
!-  end
  class Class
    alias_method :old_new,  :new
    def new(*args)
      result = old_new(*args)
      result.timestamp = Time.now
      return result
    end
  end
]]></fullcode>
class<nbsp/>Class
<nbsp/><nbsp/>alias_method<nbsp/>:old_new,<nbsp/><nbsp/>:new
<nbsp/><nbsp/>def<nbsp/>new(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>old_new(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>result.timestamp<nbsp/>=<nbsp/>Time.now
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>result
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
We'll also need to add a timestamp attribute to every object in the
system. We can do this by hacking class <classname>Object</classname> itself.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Object
    def timestamp
      return @timestamp
    end
    def timestamp=(aTime)
      @timestamp = aTime
    end
  end
!-  class Class
!-    alias_method :old_new,  :new
!-    def new(*args)
!-      result = old_new(*args)
!-      result.timestamp = Time.now
!-      return result
!-    end
!-  end
]]></fullcode>
class<nbsp/>Object
<nbsp/><nbsp/>def<nbsp/>timestamp
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@timestamp
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>timestamp=(aTime)
<nbsp/><nbsp/><nbsp/><nbsp/>@timestamp<nbsp/>=<nbsp/>aTime
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Finally, we can run a test. We'll create a couple of objects a few
seconds apart and check their timestamps.
<p/>
<codefragment>
<fullcode><![CDATA[!-  class Object
!-    def timestamp
!-      return @timestamp
!-    end
!-    def timestamp=(aTime)
!-      @timestamp = aTime
!-    end
!-  end
!-  class Class
!-    alias_method :old_new,  :new
!-    def new(*args)
!-      result = old_new(*args)
!-      result.timestamp = Time.now
!-      return result
!-    end
!-  end
  class Test
  end
  
  obj1 = Test.new
  sleep 2  #!sh!
  obj2 = Test.new

  obj1.timestamp
  obj2.timestamp
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Test</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>obj1<nbsp/>=<nbsp/>Test.new</tt></td>
</tr>
<tr>
<td colspan="3"><tt>sleep<nbsp/>2</tt></td>
</tr>
<tr>
<td colspan="3"><tt>obj2<nbsp/>=<nbsp/>Test.new</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>obj1.timestamp</tt></td>
  <td>&#187;</td>
  <td><tt>Sun<nbsp/>Jun<nbsp/>09<nbsp/>00:09:45<nbsp/>CDT<nbsp/>2002</tt></td>
</tr>
<tr>
  <td><tt>obj2.timestamp</tt></td>
  <td>&#187;</td>
  <td><tt>Sun<nbsp/>Jun<nbsp/>09<nbsp/>00:09:47<nbsp/>CDT<nbsp/>2002</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
All this method renaming is fine, and it really does work. However,
there are other, more refined ways to get inside a running
program. Ruby provides several callback methods that let you trap
certain events in a controlled way.
<subsection>Runtime Callbacks</subsection>
<p/>
You can be notified whenever one of the following events occurs:
<p/>
<table>
<th>
  <td><b>Event</b></td>
  <td><b>Callback Method</b></td>
</th>
<tr>
  <td>Adding an instance method</td>
  <td><cim><file>module</file><front>Module</front><back>method_added</back><mref>method_added</mref></cim></td>
</tr>
<tr>
  <td>Adding a singleton method</td>
  <td><mmm><file>kernel</file><front>Kernel</front><back>singleton_method_added</back><mref>singleton_method_added</mref></mmm></td>
</tr>
<tr>
  <td>Subclassing a class</td>
  <td><cim><file>class</file><front>Class</front><back>inherited</back><mref>inherited</mref></cim></td>
</tr>
<tr>
  <td>Mixing in a module</td>
  <td><cim><file>module</file><front>Module</front><back>extend_object</back><mref>extend_object</mref></cim></td>
</tr>
<bottomrule/></table>
<p/>
These techniques are all illustrated in the library descriptions for
each callback method.  At runtime, these methods will be called by the
system when the specified event occurs.  By default, these methods do
nothing. If you want to be notified when one of these events happens,
just define the callback method, and you're in.
<p/>
Keeping track of method creation and class and module usage lets you
build an accurate picture of the dynamic state of your program. This
can be important. For example, you may have written code that wraps
all the methods in a class, perhaps to add transactional support or
to implement some form of delegation. This is only half the job: the
dynamic nature of Ruby means that users of this class could add new
methods to it at any time. Using these callbacks, you can write
code that wraps these new methods as they are created.
<section>Tracing Your Program's Execution</section>
<p/>
While we're having fun reflecting on all the objects and classes in
our programs, let's not forget about the humble statements that make
our code actually do things. It turns out that Ruby lets us look at
these statements, too.
<p/>
First, you can watch the interpreter as it executes code.
<tt>set_trace_func</tt>
executes a <tt>Proc</tt> with all sorts of juicy
debugging information whenever a new source line is executed,
methods are called, objects are created, and so on. There's a full description
on page 422, but here's a taste.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Test
    def test
      a = 1
      b = 2
    end
  end
  
  set_trace_func proc { |event, file, line, id, binding, classname|
!- file = "prog.rb"
!- line -= 2 if line > __LINE__
    printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
  }
  t = Test.new
  t.test
]]></fullcode>
class<nbsp/>Test
<nbsp/><nbsp/>def<nbsp/>test
<nbsp/><nbsp/><nbsp/><nbsp/>a<nbsp/>=<nbsp/>1
<nbsp/><nbsp/><nbsp/><nbsp/>b<nbsp/>=<nbsp/>2
<nbsp/><nbsp/>end
end
<p/>
set_trace_func<nbsp/>proc<nbsp/>{<nbsp/>|event,<nbsp/>file,<nbsp/>line,<nbsp/>id,<nbsp/>binding,<nbsp/>classname|
<nbsp/><nbsp/>printf<nbsp/>"%8s<nbsp/>%s:%-2d<nbsp/>%10s<nbsp/>%8s\n",<nbsp/>event,<nbsp/>file,<nbsp/>line,<nbsp/>id,<nbsp/>classname
}
t<nbsp/>=<nbsp/>Test.new
t.test
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
<nbsp/><nbsp/><nbsp/><nbsp/>line<nbsp/>prog.rb:11<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>false
<nbsp/><nbsp/>c-call<nbsp/>prog.rb:11<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>new<nbsp/><nbsp/><nbsp/><nbsp/>Class
<nbsp/><nbsp/>c-call<nbsp/>prog.rb:11<nbsp/>initialize<nbsp/><nbsp/><nbsp/>Object
c-return<nbsp/>prog.rb:11<nbsp/>initialize<nbsp/><nbsp/><nbsp/>Object
c-return<nbsp/>prog.rb:11<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>new<nbsp/><nbsp/><nbsp/><nbsp/>Class
<nbsp/><nbsp/><nbsp/><nbsp/>line<nbsp/>prog.rb:12<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>false
<nbsp/><nbsp/><nbsp/><nbsp/>call<nbsp/>prog.rb:2<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>test<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Test
<nbsp/><nbsp/><nbsp/><nbsp/>line<nbsp/>prog.rb:3<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>test<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Test
<nbsp/><nbsp/><nbsp/><nbsp/>line<nbsp/>prog.rb:4<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>test<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Test
<nbsp/><nbsp/>return<nbsp/>prog.rb:4<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>test<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Test
</alltt>
</codefragment>
<p/>
There's also a method <tt>trace_var</tt> (described
on page 427) that lets you add a hook to a global variable; whenever
an assignment is made to the global, your <classname>Proc</classname> object is invoked.
<subsection>How Did We Get Here?</subsection>
<p/>
A fair question, and one we ask ourselves regularly.  Mental lapses
aside, in Ruby at least you can find out exactly ``how you got there''
by using the method <tt>caller</tt>,
which returns an <tt>Array</tt> of
<classname>String</classname> objects representing the current call stack.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def catA
#    puts caller.join("\n")
!-    puts caller.join("\n").gsub(/-:(\d+)/) { "prog.rb:#{$1.to_i-1}" }
  end
  def catB
    catA
  end
  def catC
    catB
  end
  catC
]]></fullcode>
def<nbsp/>catA
<nbsp/><nbsp/>puts<nbsp/>caller.join("\n")
end
def<nbsp/>catB
<nbsp/><nbsp/>catA
end
def<nbsp/>catC
<nbsp/><nbsp/>catB
end
catC
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
prog.rb:5:in<nbsp/>`catB'
prog.rb:8:in<nbsp/>`catC'
prog.rb:10
</alltt>
</codefragment>
<p/>
Once you've figured out how you got there, where you go next is up to
you.
<section>Marshaling and Distributed Ruby</section>
<p/>
Java features the ability to <em>serialize</em> objects, letting you
store them somewhere and reconstitute them when needed.  You might
use this facility, for instance, to save a tree of objects that
represent some portion of application state---a document, a CAD
drawing, a piece of music, and so on.
<p/>
Ruby calls this kind of serialization
<em>marshaling</em>.<footnote>Think of railroad marshaling yards
  where individual cars are assembled in sequence into a complete
  train, which is then dispatched somewhere.</footnote>  Saving an object
and some or all of its components is done using the method
<mmm><file>marshal</file><front>Marshal</front><back>dump</back><mref>dump</mref></mmm>.  Typically, you will dump an entire object tree
starting with some given object. Later on, you can reconstitute the
object using <mmm><file>marshal</file><front>Marshal</front><back>load</back><mref>load</mref></mmm>.
<p/>
Here's a short example. We have a class <classname>Chord</classname> that holds a
collection of musical notes. We'd like to save away a particularly
wonderful chord so our grandchildren can load it into Ruby Version
23.5 and savor it, too. Let's start off with the classes for <classname>Note</classname>
and <classname>Chord</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Note
    attr :value
    def initialize(val)
      @value = val
    end
    def to_s
      @value.to_s
    end
  end

  class Chord
    def initialize(arr)
      @arr = arr
    end
    def play
      @arr.join('-')
    end
  end
!-  c = Chord.new( [ Note.new("G"),  Note.new("Bb"),
!-                   Note.new("Db"), Note.new("E") ] )
!-
!-  File.open("posterity", "w+") do |f|
!-    Marshal.dump(c, f)
!-  end
]]></fullcode>
class<nbsp/>Note
<nbsp/><nbsp/>attr<nbsp/>:value
<nbsp/><nbsp/>def<nbsp/>initialize(val)
<nbsp/><nbsp/><nbsp/><nbsp/>@value<nbsp/>=<nbsp/>val
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>to_s
<nbsp/><nbsp/><nbsp/><nbsp/>@value.to_s
<nbsp/><nbsp/>end
end
<p/>
class<nbsp/>Chord
<nbsp/><nbsp/>def<nbsp/>initialize(arr)
<nbsp/><nbsp/><nbsp/><nbsp/>@arr<nbsp/>=<nbsp/>arr
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>play
<nbsp/><nbsp/><nbsp/><nbsp/>@arr.join('-')
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Now we'll create our masterpiece, and use <mmm><file>marshal</file><front>Marshal</front><back>dump</back><mref>dump</mref></mmm> to save
a serialized version of it to disk.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class Note
!-    attr :value
!-    def initialize(val)
!-      @value = val
!-    end
!-    def to_s
!-      @value.to_s
!-    end
!-  end
!-
!-  class Chord
!-    def initialize(arr)
!-      @arr = arr
!-    end
!-    def play
!-      @arr.join('-')
!-    end
!-  end
  c = Chord.new( [ Note.new("G"),  Note.new("Bb"),
                   Note.new("Db"), Note.new("E") ] )

  File.open("posterity", "w+") do |f|
    Marshal.dump(c, f)
  end
]]></fullcode>
c<nbsp/>=<nbsp/>Chord.new(<nbsp/>[<nbsp/>Note.new("G"),<nbsp/><nbsp/>Note.new("Bb"),
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Note.new("Db"),<nbsp/>Note.new("E")<nbsp/>]<nbsp/>)
<p/>
File.open("posterity",<nbsp/>"w+")<nbsp/>do<nbsp/>|f|
<nbsp/><nbsp/>Marshal.dump(c,<nbsp/>f)
end
</alltt>
</codefragment>
<p/>
Finally, our grandchildren read it in, and are transported by our
creation's beauty.
<p/>
<codefragment>
<fullcode><![CDATA[!-  class Note
!-    attr :value
!-    def initialize(val)
!-      @value = val
!-    end
!-    def to_s
!-      @value.to_s
!-    end
!-  end
!-
!-  class Chord
!-    def initialize(arr)
!-      @arr = arr
!-    end
!-    def play
!-      @arr.join('-')
!-    end
!-  end
!-  c = Chord.new( [ Note.new("G"),  Note.new("Bb"),
!-                   Note.new("Db"), Note.new("E") ] )
!-
!-  File.open("posterity", "w+") do |f|
!-    Marshal.dump(c, f)
!-  end
!- chord = nil
  File.open("posterity") do |f|
    chord = Marshal.load(f)
  end
  
  chord.play
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>File.open("posterity")<nbsp/>do<nbsp/>|f|</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>chord<nbsp/>=<nbsp/>Marshal.load(f)</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>chord.play</tt></td>
  <td>&#187;</td>
  <td><tt>"G-Bb-Db-E"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Custom Serialization Strategy</subsection>
<p/>
Not all objects can be dumped: bindings, procedure objects, instances
of class <classname>IO</classname>, and singleton objects cannot be saved outside of the
running Ruby environment (a <exception>TypeError</exception> will be raised if you try).
Even if your object doesn't contain one of these problematic objects,
you may want to take control of object serialization yourself.
<p/>
<modulename>Marshal</modulename> provides the hooks you need. In the objects that require
custom serialization, simply implement two methods: an instance method 
called <meth>_dump</meth>,
which writes the object out to a string, and a
class method called <meth>_load</meth>, which reads a string that you'd
previously created and converts it into a new object.
<p/>
For instance, here is a sample class that defines its own
serialization.
For whatever reasons, <classname>Special</classname> doesn't want to save one of its
internal data members, ``<tt>@volatile</tt>''.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Special
    def initialize(valuable)
      @valuable = valuable
      @volatile = "Goodbye"
    end

    def _dump(depth)
      @valuable.to_str
    end

    def Special._load(str)
      result = Special.new(str);
    end

    def to_s
      "#{@valuable} and #{@volatile}"
    end
  end

  a = Special.new("Hello, World")
  data = Marshal.dump(a)
  obj = Marshal.load(data)
  puts obj
]]></fullcode>
class<nbsp/>Special
<nbsp/><nbsp/>def<nbsp/>initialize(valuable)
<nbsp/><nbsp/><nbsp/><nbsp/>@valuable<nbsp/>=<nbsp/>valuable
<nbsp/><nbsp/><nbsp/><nbsp/>@volatile<nbsp/>=<nbsp/>"Goodbye"
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>_dump(depth)
<nbsp/><nbsp/><nbsp/><nbsp/>@valuable.to_str
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>Special._load(str)
<nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>Special.new(str);
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>to_s
<nbsp/><nbsp/><nbsp/><nbsp/>"#{@valuable}<nbsp/>and<nbsp/>#{@volatile}"
<nbsp/><nbsp/>end
end
<p/>
a<nbsp/>=<nbsp/>Special.new("Hello,<nbsp/>World")
data<nbsp/>=<nbsp/>Marshal.dump(a)
obj<nbsp/>=<nbsp/>Marshal.load(data)
puts<nbsp/>obj
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Hello,<nbsp/>World<nbsp/>and<nbsp/>Goodbye
</alltt>
</codefragment>
<p/>
For more details, see the reference section on <modulename>Marshal</modulename>
beginning on page 428.
<subsection>Distributed Ruby</subsection>
Since we can serialize an object or a set of objects into a form
suitable for out-of-process storage, we can use this capability for
the <em>transmission</em> of objects from one process to another.
Couple this capability with the power of networking, and
<em>voil&#224;</em>: you have a distributed object system.  To save you
the trouble of having to write the code, we suggest downloading
Masatoshi Seki's Distributed Ruby library (drb) from the RAA.
<p/>
Using drb, a Ruby process may act as a server, as a client, or as both. A 
drb server acts as a source of objects, while a client is a user of
those objects. To the client, it appears that the objects are local,
but in reality the code is still being executed remotely.
<p/>
A server starts a service by associating an object with a given port.
Threads are created internally to handle incoming requests on that
port, so remember to join the drb thread before exiting your program.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'drb'

  class TestServer
    def doit
      "Hello, Distributed World"
    end
  end

  aServerObject = TestServer.new
  DRb.start_service('druby://localhost:9000', aServerObject)
  DRb.thread.join # Don't exit just yet!
]]></fullcode>
require<nbsp/>'drb'
<p/>
class<nbsp/>TestServer
<nbsp/><nbsp/>def<nbsp/>doit
<nbsp/><nbsp/><nbsp/><nbsp/>"Hello,<nbsp/>Distributed<nbsp/>World"
<nbsp/><nbsp/>end
end
<p/>
aServerObject<nbsp/>=<nbsp/>TestServer.new
DRb.start_service('druby://localhost:9000',<nbsp/>aServerObject)
DRb.thread.join<nbsp/>#<nbsp/>Don't<nbsp/>exit<nbsp/>just<nbsp/>yet!
</alltt>
</codefragment>
<p/>
A simple drb client simply creates a local drb object and associates
it with the object on the remote server; the local object is a proxy.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'drb'
  DRb.start_service()
  obj = DRbObject.new(nil, 'druby://localhost:9000')
  # Now use obj
  p obj.doit
]]></fullcode>
require<nbsp/>'drb'
DRb.start_service()
obj<nbsp/>=<nbsp/>DRbObject.new(nil,<nbsp/>'druby://localhost:9000')
#<nbsp/>Now<nbsp/>use<nbsp/>obj
p<nbsp/>obj.doit
</alltt>
</codefragment>
<p/>
The client connects to the server and calls the method <tt>doit</tt>, which
returns a string that the client prints out:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  "Hello, Distributed World"
]]></fullcode>
"Hello,<nbsp/>Distributed<nbsp/>World"
</alltt>
</codefragment>
<p/>
The initial <tt>nil</tt> argument to <tt>DRbObject</tt> indicates that we want
to attach to a new distributed object.  We could also use an
existing object.
<p/>
Ho hum, you say. This sounds like Java's RMI, or CORBA, or whatever.
Yes, it is a functional distributed object mechanism---but it is
written in just 200 lines of Ruby code.  No C, nothing fancy,  just
plain old Ruby code.  Of course, there's no naming service or trader
service, or anything like you'd see in CORBA, but it is simple and
reasonably fast.  On the 233MHz test system, this sample code runs at
about 50 remote message calls per second.
<p/>
And, if you like the look of Sun's JavaSpaces, the basis of their JINI
architecture, you'll be interested to know that drb is distributed with
a short module that does the same kind of thing. JavaSpaces is based
on a technology called Linda. To prove that its Japanese author has a
sense of humor, Ruby's version of Linda is known as ``rinda.''
<section>Compile Time? Runtime? Anytime!</section>
<p/>
The important thing to remember about Ruby is that there isn't a big
difference between ``compile time'' and ``runtime.''  It's all the
same.  You can add code to a running process.  You
can redefine methods on the fly, change their scope from <tt>public</tt>
to <tt>private</tt>, and so on. You can even alter basic types,  such
as <classname>Class</classname> and <classname>Object</classname>.
<p/>
Once you get used to this flexibility, it is hard to go back to a
static language such as C++, or even to a half-static language such as
Java.
<p/>
But then, why would you want to?
</chapter>
</ppdoc>
