<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="Modules">
<p/>
Modules are
a way of grouping together methods, classes, and
constants. Modules give you two major benefits:
<ol>
<li> Modules provide a namespace and prevent name clashes.
</li><li> Modules implement the mixin facility.
</li></ol>
<section>Namespaces</section>
<p/>
As you start to write bigger and bigger Ruby programs, you'll
naturally find yourself producing chunks of reusable code---libraries
of related routines that are generally applicable. You'll want to
break this code out into separate files so the contents can be shared 
among different Ruby programs.
<p/>
Often this code will be organized into classes, so you'll probably
stick a class (or a set of interrelated classes) into a file.
<p/>
However, there are times when you want to group things together that
don't naturally form a class.
<p/>
An initial approach might be to put all these things into a file and
simply load that file into any program that needs it. This is the
way the C language works. However, there's a problem. Say you write a
set of trigonometry functions <meth>sin</meth>, <meth>cos</meth>, and so on.
You stuff them all into a file, <tt>trig.rb</tt>, for future generations
to enjoy. Meanwhile, Sally is working on a simulation of good and evil,
and codes up a set of her own useful routines, including <tt>beGood</tt>
and <meth>sin</meth>, and sticks them into <tt>action.rb</tt>. Joe, who
wants to write a program to find out how many angels can dance on the
head of a pin, needs to load both <tt>trig.rb</tt> and <tt>action.rb</tt>
into his program. But both define a method called <tt>sin</tt>. Bad news.
<p/>
The answer is the module mechanism. Modules define a namespace, a
sandbox in which your methods and constants can play without having to
worry about being stepped on by other methods and constants. The trig
functions can go into one module:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[module Trig
  PI = 3.141592654
  def Trig.sin(x)
   # ..
  end
  def Trig.cos(x)
   # ..
  end
end
]]></fullcode>
module<nbsp/>Trig
<nbsp/><nbsp/>PI<nbsp/>=<nbsp/>3.141592654
<nbsp/><nbsp/>def<nbsp/>Trig.sin(x)
<nbsp/><nbsp/><nbsp/>#<nbsp/>..
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>Trig.cos(x)
<nbsp/><nbsp/><nbsp/>#<nbsp/>..
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
and the good and bad action methods can go into another:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[module Action
  VERY_BAD = 0
  BAD      = 1
  def Action.sin(badness)
    # ...
  end
end
]]></fullcode>
module<nbsp/>Action
<nbsp/><nbsp/>VERY_BAD<nbsp/>=<nbsp/>0
<nbsp/><nbsp/>BAD<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>1
<nbsp/><nbsp/>def<nbsp/>Action.sin(badness)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Module constants are named just like class constants, with an initial
uppercase letter.
The method definitions look similar, too: these
module methods are defined just like class methods.
<p/>
If a third program wants to use these modules, it can simply load up
the two files (using the Ruby <kw>require</kw> statement, which we discuss
on page 103) and reference the qualified names.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- $: << "code"
require "trig"
require "action"

y = Trig.sin(Trig::PI/4)
wrongdoing = Action.sin(Action::VERY_BAD)
]]></fullcode>
require<nbsp/>"trig"
require<nbsp/>"action"
<p/>
y<nbsp/>=<nbsp/>Trig.sin(Trig::PI/4)
wrongdoing<nbsp/>=<nbsp/>Action.sin(Action::VERY_BAD)
</alltt>
</codefragment>
<p/>
As with class methods, you call a module method by preceding its name
with the module's name and a period, and you reference a constant
using  the module name and two colons.
<section>Mixins</section>
<p/>
Modules have another, wonderful use. At a stroke, they pretty much
eliminate the need for multiple inheritance, providing a
facility called a <em>mixin</em>.
<p/>
In the previous section's examples, we defined module methods, methods
whose names were prefixed by the module name. If this made you think of
class methods, your next thought might well be ``what happens if
I define instance methods within a module?'' Good question. A module
can't have instances, because a module isn't a class. However, you can 
<em>include</em> a module within a class definition. When this happens,
all the module's instance methods are suddenly available as methods in 
the class as well. They get <em>mixed in</em>. In fact, mixed-in modules 
effectively behave as superclasses.
<p/>
<codefragment>
<fullcode><![CDATA[!-    module D
!-      def initialize(name)
!-       @name =name
!-      end
!-      def to_s
!-        @name
!-      end
!-    end
  module Debug
!-  include D
    def whoAmI?
      "#{self.type.name} (\##{self.id}): #{self.to_s}"
    end
  end
  class Phonograph
    include Debug
    # ...
  end
  class EightTrack
    include Debug
    # ...
  end
  ph = Phonograph.new("West End Blues")
  et = EightTrack.new("Surrealistic Pillow")
  
  ph.whoAmI?
  et.whoAmI?
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>module<nbsp/>Debug</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>whoAmI?</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"#{self.type.name}<nbsp/>(\##{self.id}):<nbsp/>#{self.to_s}"</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/>Phonograph</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>Debug</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>#<nbsp/>...</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>class<nbsp/>EightTrack</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>Debug</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>#<nbsp/>...</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>ph<nbsp/>=<nbsp/>Phonograph.new("West<nbsp/>End<nbsp/>Blues")</tt></td>
</tr>
<tr>
<td colspan="3"><tt>et<nbsp/>=<nbsp/>EightTrack.new("Surrealistic<nbsp/>Pillow")</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>ph.whoAmI?</tt></td>
  <td>&#187;</td>
  <td><tt>"Phonograph<nbsp/>(#537762134):<nbsp/>West<nbsp/>End<nbsp/>Blues"</tt></td>
</tr>
<tr>
  <td><tt>et.whoAmI?</tt></td>
  <td>&#187;</td>
  <td><tt>"EightTrack<nbsp/>(#537761824):<nbsp/>Surrealistic<nbsp/>Pillow"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
By including the <modulename>Debug</modulename> module, both <classname>Phonograph</classname> and
<classname>EightTrack</classname> gain access to the <meth>whoAmI?</meth> instance method.
<p/>
A couple of points about the <kw>include</kw>
statement before we go on.
First, it has nothing to do with files. C programmers use a
preprocessor directive called <tt>#include</tt> to insert the contents of
one file into another during compilation. The Ruby <kw>include</kw>
statement simply makes a reference to a named module. If that module
is in a separate file, you must use <kw>require</kw>
to drag that
file in before using <kw>include</kw>. Second, a Ruby <kw>include</kw> does
not simply copy the module's instance methods into the class. Instead,
it makes a reference from the class to the included module. If
multiple classes include that module, they'll all point to the same
thing. If you change the definition of a method within a module, even
while your program is running, all classes that include that module
will exhibit the new behavior.<footnote>Of course, we're speaking only
  of methods here. Instance variables are always per-object, for
  example.</footnote>
<p/>
Mixins give you a wonderfully controlled way of adding functionality
to classes. However, their true power comes out when the code in the
mixin starts to interact with code in the class that uses it. Let's
take the standard Ruby mixin <modulename>Comparable</modulename> as an
example. The <modulename>Comparable</modulename> mixin can be used to add the comparison
operators (<tt>&lt;</tt>, <tt>&lt;=</tt>, <tt>==</tt>, <tt>&gt;=</tt>, and <tt>&gt;</tt>), as well as
the method <meth>between?</meth>, to a class. For this to work,
<modulename>Comparable</modulename> assumes that any class that uses it defines the
operator <tt>&lt;=&gt;</tt>. So, as a class writer, you define the one method,
<tt>&lt;=&gt;</tt>, include <modulename>Comparable</modulename>, and get six comparison functions for 
free. Let's try this with our <classname>Song</classname> class, by making the songs comparable 
based on their duration.
All we have to do is include the <modulename>Comparable</modulename> module and implement
the comparison operator <tt>&lt;=&gt;</tt>. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Song
  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
  def <=>(other)
    self.duration <=> other.duration
  end
end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>include<nbsp/>Comparable
<nbsp/><nbsp/>def<nbsp/>&lt;=&gt;(other)
<nbsp/><nbsp/><nbsp/><nbsp/>self.duration<nbsp/>&lt;=&gt;<nbsp/>other.duration
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
We can check that the results are sensible with a few test songs.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
song1 = Song.new("My Way",  "Sinatra", 225)
song2 = Song.new("Bicylops", "Fleck",  260)

song1 <=> song2
song1  <  song2
song1 ==  song1
song1  >  song2
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>song1<nbsp/>=<nbsp/>Song.new("My<nbsp/>Way",<nbsp/><nbsp/>"Sinatra",<nbsp/>225)</tt></td>
</tr>
<tr>
<td colspan="3"><tt>song2<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/><nbsp/>260)</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>song1<nbsp/>&lt;=&gt;<nbsp/>song2</tt></td>
  <td>&#187;</td>
  <td><tt>-1</tt></td>
</tr>
<tr>
  <td><tt>song1<nbsp/><nbsp/>&lt;<nbsp/><nbsp/>song2</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>song1<nbsp/>==<nbsp/><nbsp/>song1</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
  <td><tt>song1<nbsp/><nbsp/>&gt;<nbsp/><nbsp/>song2</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Finally, back on page 43 we showed an
implementation of Smalltalk's <tt>inject</tt> function, implementing it
within class <classname>Array</classname>. We promised then that we'd make it more generally
applicable. What better way than making it a mixin module?
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Inject
    def inject(n)
       each do |value|
         n = yield(n, value)
       end
       n
    end
    def sum(initial = 0)
      inject(initial) { |n, value| n + value }
    end
    def product(initial = 1)
      inject(initial) { |n, value| n * value }
    end
  end
]]></fullcode>
module<nbsp/>Inject
<nbsp/><nbsp/>def<nbsp/>inject(n)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>each<nbsp/>do<nbsp/>|value|
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>n<nbsp/>=<nbsp/>yield(n,<nbsp/>value)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>n
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>sum(initial<nbsp/>=<nbsp/>0)
<nbsp/><nbsp/><nbsp/><nbsp/>inject(initial)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>+<nbsp/>value<nbsp/>}
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>product(initial<nbsp/>=<nbsp/>1)
<nbsp/><nbsp/><nbsp/><nbsp/>inject(initial)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>*<nbsp/>value<nbsp/>}
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
We can then test this by mixing it into some built-in classes.
<p/>
<codefragment>
<fullcode><![CDATA[!-  module Inject
!-    def inject(n)
!-       each do |value|
!-         n = yield(n, value)
!-       end
!-       n
!-    end
!-    def sum(initial = 0)
!-      inject(initial) { |n, value| n + value }
!-    end
!-    def product(initial = 1)
!-      inject(initial) { |n, value| n * value }
!-    end
!-  end
  class Array
    include Inject
  end
  [ 1, 2, 3, 4, 5 ].sum
  [ 1, 2, 3, 4, 5 ].product
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Array</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>Inject</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>].sum</tt></td>
  <td>&#187;</td>
  <td><tt>15</tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>].product</tt></td>
  <td>&#187;</td>
  <td><tt>120</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
<codefragment>
<fullcode><![CDATA[!-  module Inject
!-    def inject(n)
!-       each do |value|
!-         n = yield(n, value)
!-       end
!-       n
!-    end
!-    def sum(initial = 0)
!-      inject(initial) { |n, value| n + value }
!-    end
!-    def product(initial = 1)
!-      inject(initial) { |n, value| n * value }
!-    end
!-  end
  class Range
    include Inject
  end
  (1..5).sum
  (1..5).product
  ('a'..'m').sum("Letters: ")
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Range</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>include<nbsp/>Inject</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>(1..5).sum</tt></td>
  <td>&#187;</td>
  <td><tt>15</tt></td>
</tr>
<tr>
  <td><tt>(1..5).product</tt></td>
  <td>&#187;</td>
  <td><tt>120</tt></td>
</tr>
<tr>
  <td><tt>('a'..'m').sum("Letters:<nbsp/>")</tt></td>
  <td>&#187;</td>
  <td><tt>"Letters:<nbsp/>abcdefghijklm"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
For a more extensive example of a mixin, have a look at the
documentation for the <modulename>Enumerable</modulename> module, which starts
on page 403. 
<subsection>Instance Variables in Mixins</subsection>
<p/>
People coming to Ruby from C++ often ask us, ``What happens to instance
variables in a mixin? In C++, I have to jump through some hoops to
control how variables are shared in a multiple-inheritance hierarchy.
How does Ruby handle this?''
<p/>
Well, for starters, it's not really a fair question, we tell them.
Remember how instance variables work in Ruby: the first mention of an
``@''-prefixed variable creates the instance variable <em>in the
  current object,</em> <var>self</var>.
<p/>
For a mixin, this means that the module that you mix into your
client class (the mixee?) may create instance variables in the client
object and may use <meth>attr</meth> and friends to define accessors for
these instance variables.  For instance:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Notes
    attr  :concertA
    def tuning(amt)
      @concertA = 440.0 + amt
    end
  end

  class Trumpet
    include Notes
    def initialize(tune)
      tuning(tune)
      puts "Instance method returns #{concertA}"
      puts "Instance variable is #{@concertA}"
    end
  end

  # The piano is a little flat, so we'll match it
  Trumpet.new(-5.3)
]]></fullcode>
module<nbsp/>Notes
<nbsp/><nbsp/>attr<nbsp/><nbsp/>:concertA
<nbsp/><nbsp/>def<nbsp/>tuning(amt)
<nbsp/><nbsp/><nbsp/><nbsp/>@concertA<nbsp/>=<nbsp/>440.0<nbsp/>+<nbsp/>amt
<nbsp/><nbsp/>end
end
<p/>
class<nbsp/>Trumpet
<nbsp/><nbsp/>include<nbsp/>Notes
<nbsp/><nbsp/>def<nbsp/>initialize(tune)
<nbsp/><nbsp/><nbsp/><nbsp/>tuning(tune)
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Instance<nbsp/>method<nbsp/>returns<nbsp/>#{concertA}"
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Instance<nbsp/>variable<nbsp/>is<nbsp/>#{@concertA}"
<nbsp/><nbsp/>end
end
<p/>
#<nbsp/>The<nbsp/>piano<nbsp/>is<nbsp/>a<nbsp/>little<nbsp/>flat,<nbsp/>so<nbsp/>we'll<nbsp/>match<nbsp/>it
Trumpet.new(-5.3)
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Instance<nbsp/>method<nbsp/>returns<nbsp/>434.7
Instance<nbsp/>variable<nbsp/>is<nbsp/>434.7
</alltt>
</codefragment>
<p/>
Not only do we have access to the methods defined in the mixin, but we 
get access to the necessary instance variables as well.  There's a risk here, of 
course, that different mixins may use an instance variable with
the same name and create a collision:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module MajorScales
    def majorNum
      @numNotes = 7 if @numNotes.nil?
      @numNotes # Return 7
    end
  end

  module PentatonicScales
    def pentaNum
      @numNotes = 5 if @numNotes.nil?
      @numNotes # Return 5?
    end
  end

  class ScaleDemo
    include MajorScales
    include PentatonicScales
    def initialize
      puts majorNum # Should be 7
      puts pentaNum # Should be 5
    end
  end

  ScaleDemo.new
]]></fullcode>
module<nbsp/>MajorScales
<nbsp/><nbsp/>def<nbsp/>majorNum
<nbsp/><nbsp/><nbsp/><nbsp/>@numNotes<nbsp/>=<nbsp/>7<nbsp/>if<nbsp/>@numNotes.nil?
<nbsp/><nbsp/><nbsp/><nbsp/>@numNotes<nbsp/>#<nbsp/>Return<nbsp/>7
<nbsp/><nbsp/>end
end
<p/>
module<nbsp/>PentatonicScales
<nbsp/><nbsp/>def<nbsp/>pentaNum
<nbsp/><nbsp/><nbsp/><nbsp/>@numNotes<nbsp/>=<nbsp/>5<nbsp/>if<nbsp/>@numNotes.nil?
<nbsp/><nbsp/><nbsp/><nbsp/>@numNotes<nbsp/>#<nbsp/>Return<nbsp/>5?
<nbsp/><nbsp/>end
end
<p/>
class<nbsp/>ScaleDemo
<nbsp/><nbsp/>include<nbsp/>MajorScales
<nbsp/><nbsp/>include<nbsp/>PentatonicScales
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>majorNum<nbsp/>#<nbsp/>Should<nbsp/>be<nbsp/>7
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>pentaNum<nbsp/>#<nbsp/>Should<nbsp/>be<nbsp/>5
<nbsp/><nbsp/>end
end
<p/>
ScaleDemo.new
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
7
7
</alltt>
</codefragment>
<p/>
The two bits of code that we mix in both use an instance
variable named <var>@numNotes</var>.  Unfortunately, the result is probably
not what the author intended.
<p/>
For the most part, mixin modules don't try to carry their own instance
data around---they use accessors to retrieve data from the client
object.  But if you need to create a mixin that has to have its own
state, ensure that the instance variables have unique names to
distinguish them from any other mixins in the system (perhaps by using
the module's name as part of the variable name).
<section>Iterators and the Enumerable Module</section>
<p/>
You've probably noticed that the Ruby collection classes support a
large number of operations that do various things with the
collection: traverse it, sort it, and so on. You may be thinking,
``Gee, it'd sure be nice if <em>my</em> class could support all these
neat-o features, too!'' (If you actually thought that, it's probably
time to stop watching reruns of 1960s television shows.) 
<p/>
Well, your classes <em>can</em> support all these neat-o features,
thanks to the magic of mixins and module <modulename>Enumerable</modulename>. All you have 
to do is write an iterator called <meth>each</meth>, which returns the
elements of your collection in turn. Mix in <modulename>Enumerable</modulename>, and
suddenly your class supports things such as <meth>map</meth>,
<meth>include?</meth>, and <meth>find_all?</meth>. If the objects in your collection
implement meaningful ordering semantics using the <meth>&lt;=&gt;</meth>
method, you'll also get <meth>min</meth>, <meth>max</meth>, and
<meth>sort</meth>.
<section>Including Other Files</section>
<p/>
Because Ruby makes it easy to write good, modular code, you'll often
find yourself producing small files containing some chunk of
self-contained functionality---an interface to <em>x</em>, an algorithm
to do <em>y</em>, and so on. Typically, you'll organize these files as
class or module libraries.
<p/>
Having produced these files, you'll want to incorporate them into your
new programs. Ruby has two statements that do this.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[load "filename.rb"

require "filename"
]]></fullcode>
load<nbsp/>"filename.rb"
<p/>
require<nbsp/>"filename"
</alltt>
</codefragment>
<p/>
The <meth>load</meth> method includes the named Ruby source file every
time the method is executed, whereas <meth>require</meth> loads any given
file only once.
<meth>require</meth> has additional functionality: it can load
shared binary libraries. Both routines accept relative and absolute
paths. If given a relative path (or just a plain name), they'll search
every directory in the current load path (<var>$:</var>, discussed
on page 140) for the file.
<p/>
Files loaded using <kw>load</kw> and <kw>require</kw> can, of course, include
other files, which include other files, and so on.  What might
<em>not</em> be obvious is that <kw>require</kw> is an executable
statement---it may be inside an <kw>if</kw> statement, or it may include a
string that was just built.  The search path can be altered at runtime
as well.  Just add the directory you want to the string <var>$:</var>.
<p/>
Since <meth>load</meth> will include the source unconditionally, you can
use it to reload a source file that may have changed since the
program began:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  5.times do |i|
     File.open("temp.rb","w") { |f| 
       f.puts "module Temp\ndef Temp.var() #{i}; end\nend" 
     }
     load "temp.rb"
     puts Temp.var
   end
]]></fullcode>
5.times<nbsp/>do<nbsp/>|i|
<nbsp/><nbsp/><nbsp/>File.open("temp.rb","w")<nbsp/>{<nbsp/>|f|
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>f.puts<nbsp/>"module<nbsp/>Temp\ndef<nbsp/>Temp.var()<nbsp/>#{i};<nbsp/>end\nend"
<nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/><nbsp/>load<nbsp/>"temp.rb"
<nbsp/><nbsp/><nbsp/>puts<nbsp/>Temp.var
<nbsp/>end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0
1
2
3
4
</alltt>
</codefragment>
<p/>
</chapter>
</ppdoc>
