<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="Containers, Blocks, and Iterators">
A jukebox with one song is unlikely to be popular (except perhaps in
some very, very scary bars), so pretty soon we'll have to start thinking about
producing a catalog of available songs and a playlist of songs waiting
to be played. Both of these are containers: objects that hold
references to one or more other objects.
<p/>
Both the catalog and the playlist need a similar set of methods: add a
song, remove a song, return a list of songs, and so on. The playlist
may perform additional tasks, such as inserting advertising every so
often or keeping track of cumulative play time, but we'll worry
about these things later. In the meantime, it seems like a good idea
to develop some kind of generic <classname>SongList</classname> class, which we can
specialize into catalogs and playlists.
<section>Containers</section>
<p/>
Before we start implementing, we'll need to work out how to store the
list of songs inside a <classname>SongList</classname> object. We have three obvious
choices. We could use the Ruby <classname>Array</classname> type, use the Ruby <classname>Hash</classname> type, 
or create our own list structure. Being lazy, for now we'll
look at arrays and hashes, and choose one of these for our class.
<subsection>Arrays</subsection>
<p/>
The class <classname>Array</classname> holds a collection of object references.
Each
object reference occupies a position in the array, identified by a
non-negative integer index.
<p/>
You can create arrays using literals or by explicitly creating an
<classname>Array</classname> object. A literal array is simply a list of objects between
square brackets.
<p/>
<codefragment>
<fullcode><![CDATA[  a = [ 3.14159, "pie", 99 ]
  a.type
  a.length
  a[0]
  a[1]
  a[2]
  a[3]

  b = Array.new
  b.type
  b.length
  b[0] = "second"
  b[1] = "array"
  b
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>3.14159,<nbsp/>"pie",<nbsp/>99<nbsp/>]</tt></td>
</tr>
<tr>
  <td><tt>a.type</tt></td>
  <td>&#187;</td>
  <td><tt>Array</tt></td>
</tr>
<tr>
  <td><tt>a.length</tt></td>
  <td>&#187;</td>
  <td><tt>3</tt></td>
</tr>
<tr>
  <td><tt>a[0]</tt></td>
  <td>&#187;</td>
  <td><tt>3.14159</tt></td>
</tr>
<tr>
  <td><tt>a[1]</tt></td>
  <td>&#187;</td>
  <td><tt>"pie"</tt></td>
</tr>
<tr>
  <td><tt>a[2]</tt></td>
  <td>&#187;</td>
  <td><tt>99</tt></td>
</tr>
<tr>
  <td><tt>a[3]</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>b<nbsp/>=<nbsp/>Array.new</tt></td>
</tr>
<tr>
  <td><tt>b.type</tt></td>
  <td>&#187;</td>
  <td><tt>Array</tt></td>
</tr>
<tr>
  <td><tt>b.length</tt></td>
  <td>&#187;</td>
  <td><tt>0</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b[0]<nbsp/>=<nbsp/>"second"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b[1]<nbsp/>=<nbsp/>"array"</tt></td>
</tr>
<tr>
  <td><tt>b</tt></td>
  <td>&#187;</td>
  <td><tt>["second",<nbsp/>"array"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Arrays are indexed using the <tt>[]</tt> operator.
As with most Ruby
operators, this is actually a method (in class <classname>Array</classname>) and hence
can be overridden in subclasses. As the example shows, array indices
start at zero. Index an array with a single integer, and it returns
the object at that position or returns <tt>nil</tt> if nothing's there.
Index an array with a negative integer, and it counts from the
end. This is shown in Figure 4.1 on page 35.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
<codefragment>
<fullcode><![CDATA[  a = [ 1, 3, 5, 7, 9 ]
  a[-1]
  a[-2]
  a[-99]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
  <td><tt>a[-1]</tt></td>
  <td>&#187;</td>
  <td><tt>9</tt></td>
</tr>
<tr>
  <td><tt>a[-2]</tt></td>
  <td>&#187;</td>
  <td><tt>7</tt></td>
</tr>
<tr>
  <td><tt>a[-99]</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can also index arrays with a pair of numbers, <tt>[start,<nbsp/>count]</tt>.
This returns a new array consisting of references to <tt>count</tt> objects
starting at position <tt>start</tt>.
<p/>
<codefragment>
<fullcode><![CDATA[  a = [ 1, 3, 5, 7, 9 ]
  a[1, 3]
  a[3, 1]
  a[-3, 2]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
  <td><tt>a[1,<nbsp/>3]</tt></td>
  <td>&#187;</td>
  <td><tt>[3,<nbsp/>5,<nbsp/>7]</tt></td>
</tr>
<tr>
  <td><tt>a[3,<nbsp/>1]</tt></td>
  <td>&#187;</td>
  <td><tt>[7]</tt></td>
</tr>
<tr>
  <td><tt>a[-3,<nbsp/>2]</tt></td>
  <td>&#187;</td>
  <td><tt>[5,<nbsp/>7]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Finally, you can index arrays using ranges, in which start and end
positions are separated by two or three periods. The two-period form
includes the end position, while the three-period form does not.
<p/>
<codefragment>
<fullcode><![CDATA[  a = [ 1, 3, 5, 7, 9 ]
  a[1..3]
  a[1...3]
  a[3..3]
  a[-3..-1]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
  <td><tt>a[1..3]</tt></td>
  <td>&#187;</td>
  <td><tt>[3,<nbsp/>5,<nbsp/>7]</tt></td>
</tr>
<tr>
  <td><tt>a[1...3]</tt></td>
  <td>&#187;</td>
  <td><tt>[3,<nbsp/>5]</tt></td>
</tr>
<tr>
  <td><tt>a[3..3]</tt></td>
  <td>&#187;</td>
  <td><tt>[7]</tt></td>
</tr>
<tr>
  <td><tt>a[-3..-1]</tt></td>
  <td>&#187;</td>
  <td><tt>[5,<nbsp/>7,<nbsp/>9]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The <tt>[]</tt> operator has a corresponding <tt>[]=</tt> operator, which
lets you set elements in the array. If used with a single integer
index, the element at that position is replaced by whatever is on the
right-hand side of the assignment. Any gaps that result will be filled
with <tt>nil</tt>.
<p/>
<codefragment>
  <table>
<tr>
  <td>a = [ 1, 3, 5, 7, 9 ]</td>
  <td>&#187;</td>
  <td>[1, 3, 5, 7, 9]</td>
</tr>
<tr>
  <td>a[1] = 'bat'</td>
  <td>&#187;</td>
  <td>[1, "bat", 5, 7, 9]</td>
</tr>
<tr>
  <td>a[-3] = 'cat'</td>
  <td>&#187;</td>
  <td>[1, "bat", "cat", 7, 9]</td>
</tr>
<tr>
  <td>a[3]  = [ 9, 8 ]</td>
  <td>&#187;</td>
  <td>[1, "bat", "cat", [9, 8], 9]</td>
</tr>
<tr>
  <td>a[6]  = 99</td>
  <td>&#187;</td>
  <td>[1, "bat", "cat", [9, 8], 9, nil, 99]</td>
</tr>
</table>
<p/>
</codefragment>
<p/>
If the index to <tt>[]=</tt> is two numbers (a start and a length) or a
range, then those elements in the original array are replaced by
whatever is on the right-hand side of the assignment. If the length is
zero, the right-hand side is inserted into the array before the start
position; no elements are removed. If the right-hand side is itself an
array, its elements are used in the replacement.
The array size is automatically adjusted if the index selects a
different number of elements than are available on the right-hand side
of the assignment.
<p/>
<codefragment>
  <table>
<tr>
  <td>a = [ 1, 3, 5, 7, 9 ]</td>
  <td>&#187;</td>
  <td>[1, 3, 5, 7, 9]</td>
</tr>
<tr>
  <td>a[2, 2] = 'cat'</td>
  <td>&#187;</td>
  <td>[1, 3, "cat", 9]</td>
</tr>
<tr>
  <td>a[2, 0] = 'dog'</td>
  <td>&#187;</td>
  <td>[1, 3, "dog", "cat", 9]</td>
</tr>
<tr>
  <td>a[1, 1] = [ 9, 8,  7 ]</td>
  <td>&#187;</td>
  <td>[1, 9, 8, 7, "dog", "cat", 9]</td>
</tr>
<tr>
  <td>a[0..3] = []</td>
  <td>&#187;</td>
  <td>["dog", "cat", 9]</td>
</tr>
<tr>
  <td>a[5]    = 99</td>
  <td>&#187;</td>
  <td>["dog", "cat", 9, nil, nil, 99]</td>
</tr>
</table>
<p/>
</codefragment>
<p/>
Arrays have a large number of other useful methods. Using these,
you can treat arrays as stacks, sets, queues,
dequeues, and fifos. A complete list of array methods starts
on page 278.
<subsection>Hashes</subsection>
<p/>
Hashes (sometimes known as associative arrays or dictionaries) are
similar to arrays, in that they are indexed collectives of object
references.
<p/>
However, while you index arrays with integers, you can
index a hash with objects of any type: strings, regular expressions,
and so on. When you store a value in a hash, you actually supply two
objects---the key and the value. You can subsequently retrieve the
value by indexing the hash with the same key. The values in a hash can
be any objects of any type. The example that follows uses hash literals: a
list of <em>key</em><nbsp/><tt>=&gt;</tt><nbsp/><em>value</em> pairs between braces.
<p/>
<codefragment>
<fullcode><![CDATA[  h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }

  h.length
  h['dog']
  h['cow'] = 'bovine'
  h[12]    = 'dodecine'
  h['cat'] = 99
  h
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>h<nbsp/>=<nbsp/>{<nbsp/>'dog'<nbsp/>=&gt;<nbsp/>'canine',<nbsp/>'cat'<nbsp/>=&gt;<nbsp/>'feline',<nbsp/>'donkey'<nbsp/>=&gt;<nbsp/>'asinine'<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>h.length</tt></td>
  <td>&#187;</td>
  <td><tt>3</tt></td>
</tr>
<tr>
  <td><tt>h['dog']</tt></td>
  <td>&#187;</td>
  <td><tt>"canine"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h['cow']<nbsp/>=<nbsp/>'bovine'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h[12]<nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>'dodecine'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h['cat']<nbsp/>=<nbsp/>99</tt></td>
</tr>
<tr>
  <td><tt>h</tt></td>
  <td>&#187;</td>
  <td><tt>{"donkey"=&gt;"asinine",<nbsp/>"cow"=&gt;"bovine",<nbsp/>"dog"=&gt;"canine",<nbsp/>12=&gt;"dodecine",<nbsp/>"cat"=&gt;99}</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Compared with arrays, hashes have one significant advantage: they can
use any object as an index. However, they also have a significant
disadvantage: their elements are not ordered, so you cannot easily use 
a hash as a stack or a queue.
<p/>
You'll find that hashes are one of the most commonly used data
structures in Ruby. A full list of the methods implemented by class
<classname>Hash</classname> starts on page 317.
<subsection>Implementing a SongList Container</subsection>
<p/>
After that little diversion into arrays and hashes, we're now ready to
implement the jukebox's <classname>SongList</classname>.  Let's invent a basic list of
methods we need in our <classname>SongList</classname>. We'll want to add to it as we go
along, but it will do for now.
<p/>
<dl>
  <dt>append( aSong ) &#187; list</dt><dd>
  Append the given song to the list.
  </dd><dt>deleteFirst() &#187; aSong</dt><dd>
  Remove the first song from the list, returning that song.
  </dd><dt>deleteLast() &#187; aSong</dt><dd>
  Remove the last song from the list, returning that song.
  </dd><dt>[ anIndex } &#187; aSong</dt><dd>
  Return the song identified by <obj>anIndex</obj>, which may be an
  integer index or a song title.
</dd></dl>
<p/>
This list gives us a clue to the implementation. The ability to append
songs at the end, and remove them from both the front and end, suggests a
dequeue---a double-ended queue---which we know we can implement using
an <classname>Array</classname>. Similarly, the ability to return a song at an integer
position in the list is supported by arrays.
<p/>
However, there's also the 
need to be able to retrieve songs by title, which might suggest using a
hash, with the title as a key and the song as a value. Could we use a
hash? Well, possibly, but there are problems. First a hash is
unordered, so we'd probably need to use an ancillary array to keep
track of the list. A bigger problem is that a hash does not support
multiple keys with the same value. That would be a problem for our
playlist, where the same song might be queued up for playing multiple
times. So, for now we'll stick with an array of songs, searching it
for titles when needed. If this becomes a performance bottleneck, we
can always add some kind of hash-based lookup later.
<p/>
We'll start our class with a basic <meth>initialize</meth> method, which
creates the <classname>Array</classname> we'll use to hold the songs and stores a
reference to it in the instance variable <var>@songs</var>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
  def initialize
    @songs = Array.new
!-    @index = WordIndex.new
  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>@songs<nbsp/>=<nbsp/>Array.new
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The <cim><front>SongList</front><back>append</back></cim> method adds the given song to the end of the 
<var>@songs</var> array. It also returns <obj>self</obj>, a reference to the
current <classname>SongList</classname> object. This is a useful convention, as it lets
us chain together multiple calls to <meth>append</meth>. We'll see an
example of this later.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
  def append(aSong)
    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
    self
  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>append(aSong)
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.push(aSong)
<nbsp/><nbsp/><nbsp/><nbsp/>self
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Then we'll add the <meth>deleteFirst</meth> and <meth>deleteLast</meth>
methods, trivially implemented using <cim><file>array</file><front>Array</front><back>shift</back><mref>shift</mref></cim> and
<cim><file>array</file><front>Array</front><back>pop</back><mref>pop</mref></cim>, respectively.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
  def deleteFirst
    @songs.shift
  end
  def deleteLast
    @songs.pop
  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>deleteFirst
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.shift
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>deleteLast
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.pop
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
At this point, a quick test might be in order. First, we'll append
four songs to the list. Just to show off, we'll use the fact that
<meth>append</meth> returns the <classname>SongList</classname> object to chain together
these method calls.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
!-class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
!-end  
!-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
list = SongList.new
list.
  append(Song.new('title1', 'artist1', 1)).
  append(Song.new('title2', 'artist2', 2)).
  append(Song.new('title3', 'artist3', 3)).
  append(Song.new('title4', 'artist4', 4))
!-list[0]
!-list[2]
!-list[9]
!-list.deleteFirst
!-list.deleteFirst
!-list.deleteLast
!-list.deleteLast
!-list.deleteLast
]]></fullcode>
list<nbsp/>=<nbsp/>SongList.new
list.
<nbsp/><nbsp/>append(Song.new('title1',<nbsp/>'artist1',<nbsp/>1)).
<nbsp/><nbsp/>append(Song.new('title2',<nbsp/>'artist2',<nbsp/>2)).
<nbsp/><nbsp/>append(Song.new('title3',<nbsp/>'artist3',<nbsp/>3)).
<nbsp/><nbsp/>append(Song.new('title4',<nbsp/>'artist4',<nbsp/>4))
</alltt>
</codefragment>
<p/>
Then we'll check that songs are taken from the start and end of the
list correctly, and that <tt>nil</tt> is returned when the list becomes
empty.
<p/>
<codefragment>
<fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
!-class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
!-end  
!-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
!-list = SongList.new
!-list.
!-  append(Song.new('title1', 'artist1', 1)).
!-  append(Song.new('title2', 'artist2', 2)).
!-  append(Song.new('title3', 'artist3', 3)).
!-  append(Song.new('title4', 'artist4', 4))
!-list[0]
!-list[2]
!-list[9]
list.deleteFirst
list.deleteFirst
list.deleteLast
list.deleteLast
list.deleteLast
]]></fullcode><rubycode>
<tr>
  <td><tt>list.deleteFirst</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title1--artist1<nbsp/>(1)</tt></td>
</tr>
<tr>
  <td><tt>list.deleteFirst</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title2--artist2<nbsp/>(2)</tt></td>
</tr>
<tr>
  <td><tt>list.deleteLast</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title4--artist4<nbsp/>(4)</tt></td>
</tr>
<tr>
  <td><tt>list.deleteLast</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title3--artist3<nbsp/>(3)</tt></td>
</tr>
<tr>
  <td><tt>list.deleteLast</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
So far so good. Our next method is <tt>[]</tt>, which accesses elements
by index. If the index is a number (which we check using
<cim><file>object</file><front>Object</front><back>kind_of?</back><mref>kind_of_qm</mref></cim>), we just return the
element at that position.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
  def [](key)
    if key.kind_of?(Integer)
      @songs[key]
    else
      # ...
    end
  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Again, testing this is pretty trivial.
<p/>
<codefragment>
<fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
!-class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
!-end  
!-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
!-list = SongList.new
!-list.
!-  append(Song.new('title1', 'artist1', 1)).
!-  append(Song.new('title2', 'artist2', 2)).
!-  append(Song.new('title3', 'artist3', 3)).
!-  append(Song.new('title4', 'artist4', 4))
list[0]
list[2]
list[9]
!-list.deleteFirst
!-list.deleteFirst
!-list.deleteLast
!-list.deleteLast
!-list.deleteLast
]]></fullcode><rubycode>
<tr>
  <td><tt>list[0]</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title1--artist1<nbsp/>(1)</tt></td>
</tr>
<tr>
  <td><tt>list[2]</tt></td>
  <td>&#187;</td>
  <td><tt>Song:<nbsp/>title3--artist3<nbsp/>(3)</tt></td>
</tr>
<tr>
  <td><tt>list[9]</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Now we need to add the facility that lets us look up a song by
title. This is going to involve scanning through the songs in the
list, checking the title of each. To do this, we first need to spend a 
couple of pages looking at one of Ruby's neatest features: iterators.<section>Blocks and Iterators</section>
<p/>
So, our next problem with <classname>SongList</classname> is to implement the code in
method <meth>[]</meth> that takes a string and searches for a song with
that title. This seems straightforward: we have an array of songs, so
we just go through it one element at a time, looking for a match.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
!-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
class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
  def [](key)
    if key.kind_of?(Integer)
      return @songs[key]
    else
      for i in 0...@songs.length
        return @songs[i] if key == @songs[i].name
      end
    end
    return nil
  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>for<nbsp/>i<nbsp/>in<nbsp/>0...@songs.length
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[i]<nbsp/>if<nbsp/>key<nbsp/>==<nbsp/>@songs[i].name
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>nil
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This works, and it looks comfortingly familiar: a <tt>for</tt> loop
iterating over an array. What could be more natural?
<p/>
It turns out there <em>is</em> something more natural. In a way,
our <kw>for</kw> loop is somewhat too intimate with the array; it asks for
a length, then retrieves values in turn until it finds a match. Why
not just ask the array to apply a test to each of its members?
That's just what the <tt>find</tt> method in <classname>Array</classname> does.
<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
!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
  def [](key)
    if key.kind_of?(Integer)
      result = @songs[key]
    else
      result = @songs.find { |aSong| key == aSong.name }
    end
    return result
  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
end  
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>@songs.find<nbsp/>{<nbsp/>|aSong|<nbsp/>key<nbsp/>==<nbsp/>aSong.name<nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>result
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
We could use <tt>if</tt> as a statement modifier to shorten the
code even more.
<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
!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
  def [](key)
    return @songs[key] if key.kind_of?(Integer)
    return @songs.find { |aSong| aSong.name == key }
  end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[key]<nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs.find<nbsp/>{<nbsp/>|aSong|<nbsp/>aSong.name<nbsp/>==<nbsp/>key<nbsp/>}
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The method <meth>find</meth> is an iterator---a method that invokes a
block of code repeatedly. Iterators and code blocks are among the
more interesting features of Ruby, so let's spend a while looking into
them (and in the process we'll find out exactly what that line of code
in our <tt>[]</tt> method actually does).
<subsection>Implementing Iterators</subsection>
<p/>
A Ruby iterator is simply a method that can invoke a block of code.
At first sight, a block in Ruby looks just like a block in C, Java,
or Perl. Unfortunately, in this case looks are deceiving---a Ruby
block <em>is</em> a way of grouping statements, but not in the
conventional way.
<p/>
First, a block may appear only in the source adjacent to a method
call; the block is written starting on the same line as the method's
last parameter. Second, the code in the block is not executed at the
time it is encountered. Instead, Ruby remembers the context in which
the block appears (the local variables, the current object, and so
on), and then enters the method. This is where the magic starts.
<p/>
Within the method, the block may be invoked, almost as if it were a
method itself, using the <kw>yield</kw> statement.
Whenever a <kw>yield</kw>
is executed, it invokes the code in the block. When the block
exits, control picks back up immediately after the
<kw>yield</kw>.<footnote>Programming-language buffs will be pleased to
  know that the keyword <kw>yield</kw> was chosen to echo the <kw>yield</kw>
  function in Liskov's language CLU, a language that is over 20
  years old and yet contains features that still haven't been widely
  exploited by the CLU-less.</footnote>  Let's start with a trivial example.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def threeTimes
    yield
    yield
    yield
  end
  threeTimes { puts "Hello" }
]]></fullcode>
def<nbsp/>threeTimes
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>yield
end
threeTimes<nbsp/>{<nbsp/>puts<nbsp/>"Hello"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Hello
Hello
Hello
</alltt>
</codefragment>
<p/>
The block (the code between the braces) is associated with the call to
the method <meth>threeTimes</meth>. Within this method, <kw>yield</kw> is
called three times in a row. Each time, it invokes the code in the
block, and a cheery greeting is printed. What makes blocks interesting,
however, is that you can pass parameters to them and receive values
back from them. For example, we could write a simple function that
returns members of the Fibonacci series up to a certain
value.<footnote>The basic Fibonacci series is a sequence of integers,
  starting with two 1's, in which each subsequent term is the sum
  of the two preceding terms. The series is sometimes used in sorting
  algorithms and in analyzing natural phenomena.</footnote>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[def fibUpTo(max)
  i1, i2 = 1, 1        # parallel assignment
  while i1 <= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end
fibUpTo(1000) { |f| print f, " " }
!- puts
]]></fullcode>
def<nbsp/>fibUpTo(max)
<nbsp/><nbsp/>i1,<nbsp/>i2<nbsp/>=<nbsp/>1,<nbsp/>1<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>parallel<nbsp/>assignment
<nbsp/><nbsp/>while<nbsp/>i1<nbsp/>&lt;=<nbsp/>max
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>i1
<nbsp/><nbsp/><nbsp/><nbsp/>i1,<nbsp/>i2<nbsp/>=<nbsp/>i2,<nbsp/>i1+i2
<nbsp/><nbsp/>end
end
fibUpTo(1000)<nbsp/>{<nbsp/>|f|<nbsp/>print<nbsp/>f,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>5<nbsp/>8<nbsp/>13<nbsp/>21<nbsp/>34<nbsp/>55<nbsp/>89<nbsp/>144<nbsp/>233<nbsp/>377<nbsp/>610<nbsp/>987
</alltt>
</codefragment>
<p/>
In this example, the <kw>yield</kw> statement has a parameter.
This value
is passed to the associated block. In the definition of the block, the
argument list appears between vertical bars. In this instance, the
variable <var>f</var> receives the value passed to the <kw>yield</kw>, so the
block prints successive members of the series. (This example also
shows parallel assignment in action. We'll come back to this
on page 75.)  Although it is common to pass just one
value to a block, this is not a requirement; a block may have any
number of arguments. What happens if a block has a different number
of parameters than are given to the yield? By a staggering
coincidence, the rules we discuss under parallel assignment come into
play (with a slight twist: multiple parameters passed to a <kw>yield</kw>
are converted to an array if the block has just one argument).
<p/>
Parameters to a block may be existing local variables; if so, the new value of the variable will be
retained after the block completes.  This may lead to unexpected
behavior, but there is also a performance gain to be had by using
variables that already exist.<footnote>For more information on this
  and other ``gotchas,'' see the list beginning
  on page 127; more performance information begins
  on page 128.</footnote>
<p/>
A block may also return a value to the method. The value of the last
expression evaluated in the block is passed back to the method as the
value of the <tt>yield</tt>. This is how the <meth>find</meth> method used by class
<classname>Array</classname> works.<footnote>The <meth>find</meth> method is actually defined
  in module <modulename>Enumerable</modulename>, which is mixed into class <classname>Array</classname>.</footnote> Its
implementation would look something like the following.
<p/>
<codefragment>
<fullcode><![CDATA[class Array
  def find
    for i in 0...size
      value = self[i]
      return value if yield(value)
    end
    return nil
  end
end

[1, 3, 5, 7, 9].find {|v| v*v > 30 }
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Array</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>find</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>for<nbsp/>i<nbsp/>in<nbsp/>0...size</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>value<nbsp/>=<nbsp/>self[i]</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>value<nbsp/>if<nbsp/>yield(value)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>nil</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>[1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9].find<nbsp/>{|v|<nbsp/>v*v<nbsp/>&gt;<nbsp/>30<nbsp/>}</tt></td>
  <td>&#187;</td>
  <td><tt>7</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This passes successive elements of the array to the associated block. If
the block returns <const>true</const>, the method returns the corresponding
element. If no element matches, the method returns <tt>nil</tt>. The example shows
the benefit of this approach to iterators. The <classname>Array</classname> class does
what it does best, accessing array elements, leaving the application
code to concentrate on its particular requirement (in this case,
finding an entry that meets some mathematical criteria).
<p/>
Some iterators are common to many types of Ruby collections. We've
looked at <meth>find</meth> already. Two others are <meth>each</meth> and
<meth>collect</meth>.
<meth>each</meth> is probably the simplest iterator---all it does is yield
successive elements of its collection.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  [ 1, 3, 5 ].each { |i| puts i }
!-puts
]]></fullcode>
[<nbsp/>1,<nbsp/>3,<nbsp/>5<nbsp/>].each<nbsp/>{<nbsp/>|i|<nbsp/>puts<nbsp/>i<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1
3
5
<p/>
</alltt>
</codefragment>
<p/>
The <meth>each</meth> iterator has a special place in Ruby;
on page
85 we'll describe how it's used as the basis of the
language's <kw>for</kw> loop, and starting on page 102 we'll see how
defining an <meth>each</meth> method can add a whole lot more
functionality to your class for free.
<p/>
Another common iterator is <meth>collect</meth>, which takes each element
from the collection and passes it to the block. The results returned
by the block are
used to construct a new array.  For instance:
<p/>
<codefragment>
<fullcode><![CDATA[  ["H", "A", "L"].collect { |x| x.succ }
]]></fullcode><rubycode>
<tr>
  <td><tt>["H",<nbsp/>"A",<nbsp/>"L"].collect<nbsp/>{<nbsp/>|x|<nbsp/>x.succ<nbsp/>}</tt></td>
  <td>&#187;</td>
  <td><tt>["I",<nbsp/>"B",<nbsp/>"M"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Ruby Compared with C++ and Java</subsection>
<p/>
It's worth spending a paragraph comparing Ruby's approach to iterators
to that of C++ and Java. In the Ruby approach, the iterator is simply
a method, identical to any other, that happens to call <kw>yield</kw>
whenever it generates a new value. The thing that uses the iterator is
simply a block of code associated with this method. There is no need
to generate helper classes to carry the iterator state, as in Java and
C++. In this, as in many other ways, Ruby is a transparent
language.
When you write a Ruby program, you concentrate on getting
the job done, not on building scaffolding to support the language
itself.
<p/>
Iterators are not limited to accessing existing data in arrays and
hashes. As we saw in the Fibonacci example, an iterator can return
derived values. This capability is used by the Ruby input/output
classes, which implement
an iterator interface returning successive lines (or bytes) in an I/O
stream.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  f = File.open("testfile")
  f.each do |line|
    print line
  end
  f.close
]]></fullcode>
f<nbsp/>=<nbsp/>File.open("testfile")
f.each<nbsp/>do<nbsp/>|line|
<nbsp/><nbsp/>print<nbsp/>line
end
f.close
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>line<nbsp/>one
This<nbsp/>is<nbsp/>line<nbsp/>two
This<nbsp/>is<nbsp/>line<nbsp/>three
And<nbsp/>so<nbsp/>on...
</alltt>
</codefragment>
<p/>
Let's look at just one more iterator implementation. The Smalltalk
language also supports iterators over collections. If you ask 
Smalltalk programmers to sum the elements in an array, it's likely that
they'd use the <meth>inject</meth> function.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[sumOfValues              "Smalltalk method"
    ^self values
          inject: 0
          into: [ :sum :element | sum + element value]
]]></fullcode>
sumOfValues<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Smalltalk<nbsp/>method"
<nbsp/><nbsp/><nbsp/><nbsp/>^self<nbsp/>values
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>inject:<nbsp/>0
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>into:<nbsp/>[<nbsp/>:sum<nbsp/>:element<nbsp/>|<nbsp/>sum<nbsp/>+<nbsp/>element<nbsp/>value]
</alltt>
</codefragment>
<p/>
<meth>inject</meth> works like this. The first time the associated block
is called, <var>sum</var> is set to <meth>inject</meth>'s parameter (zero in this case),
and <var>element</var> is set to the first element in the array. The second
and subsequent times the block is called, <var>sum</var> is set to the
value returned by the block on the previous call. This way, <var>sum</var>
can be used to keep a running total. The final value of <meth>inject</meth> is the
value returned by the block the last time it was called.
<p/>
Ruby does not have an <meth>inject</meth> method, but
it's easy to write one. In this case we'll add it to the <classname>Array</classname>
class, while on page 100 we'll see how to make it more
generally available.
<p/>
<codefragment>
<fullcode><![CDATA[  class Array
    def inject(n)
       each { |value| n = yield(n, value) }
       n
    end
    def sum
      inject(0) { |n, value| n + value }
    end
    def product
      inject(1) { |n, value| n * value }
    end
  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/>def<nbsp/>inject(n)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>each<nbsp/>{<nbsp/>|value|<nbsp/>n<nbsp/>=<nbsp/>yield(n,<nbsp/>value)<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>n</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>sum</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>inject(0)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>+<nbsp/>value<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>product</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>inject(1)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>*<nbsp/>value<nbsp/>}</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>[<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/>
Although blocks are often the target of an iterator, they also have
other uses. Let's look at a few.
<subsection>Blocks for Transactions</subsection>
<p/>
Blocks can be used to define a chunk of code that must be run under
some kind of transactional control.
For example, you'll often open a
file, do something with its contents, and then want to ensure that the
file is closed when you finish. Although you can do this using
conventional code, there's an argument for making the file responsible
for closing itself. We can do this with blocks. A naive implementation 
(ignoring error handling) might look something like the following.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class File
    def File.openAndProcess(*args)
      f = File.open(*args)
      yield f
      f.close()
    end
  end

  File.openAndProcess("testfile", "r") do |aFile|
    print while aFile.gets
  end
]]></fullcode>
class<nbsp/>File
<nbsp/><nbsp/>def<nbsp/>File.openAndProcess(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>f<nbsp/>=<nbsp/>File.open(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>f
<nbsp/><nbsp/><nbsp/><nbsp/>f.close()
<nbsp/><nbsp/>end
end
<p/>
File.openAndProcess("testfile",<nbsp/>"r")<nbsp/>do<nbsp/>|aFile|
<nbsp/><nbsp/>print<nbsp/>while<nbsp/>aFile.gets
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>line<nbsp/>one
This<nbsp/>is<nbsp/>line<nbsp/>two
This<nbsp/>is<nbsp/>line<nbsp/>three
And<nbsp/>so<nbsp/>on...
</alltt>
</codefragment>
<p/>
This small example illustrates a number of techniques. The
<meth>openAndProcess</meth> method is a <em>class method</em>---it may be
called independent of any particular <classname>File</classname> object. We want it to
take the same arguments as the conventional <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> method,
but we don't really care what those arguments are. Instead, we
specified the arguments as <tt>*args</tt>, meaning ``collect the actual
parameters passed to the method into an array.'' We then call
<tt>File.open</tt>, passing it <tt>*args</tt> as a parameter. This expands the
array back into individual parameters. The net result is that
<tt>openAndProcess</tt> transparently passes whatever parameters it
received to <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm>.
<p/>
Once the file has been opened, <tt>openAndProcess</tt> calls <meth>yield</meth>,
passing the open file object to the block. When the block returns, the 
file is closed. In this way, the responsibility for closing an open
file has been passed from the user of file objects back to the files
themselves.
<p/>
Finally, this example uses <kw>do</kw>...<kw>end</kw> to define a block. The only
difference between this notation and using braces to define blocks is
precedence: <kw>do</kw>...<kw>end</kw> binds lower than ``{...}''. We
discuss the impact of this on page 234.
<p/>
The technique of having files manage their own lifecycle is so useful
that the class <classname>File</classname> supplied with Ruby supports it directly. If
<ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> has an associated block, then that block will be
invoked with a file object, and the file will be closed when the block
terminates. This is interesting, as it means that <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> has
two different behaviors: when called with a block, it executes the
block and closes the file. When called without a block, it returns the 
file object. This is made possible by the method
<mmm><file>kernel</file><front>Kernel</front><back>block_given?</back><mref>block_given_qm</mref></mmm>, which returns <const>true</const> if a block is associated
with the current method. Using it, you could implement <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> 
(again, ignoring error handling) using something like the following.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class File
    def File.myOpen(*args)
      aFile = File.new(*args)
      # If there's a block, pass in the file and close
      # the file when it returns
      if block_given?
        yield aFile
        aFile.close
        aFile = nil
      end
      return aFile
    end
  end
]]></fullcode>
class<nbsp/>File
<nbsp/><nbsp/>def<nbsp/>File.myOpen(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>aFile<nbsp/>=<nbsp/>File.new(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>If<nbsp/>there's<nbsp/>a<nbsp/>block,<nbsp/>pass<nbsp/>in<nbsp/>the<nbsp/>file<nbsp/>and<nbsp/>close
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>the<nbsp/>file<nbsp/>when<nbsp/>it<nbsp/>returns
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>block_given?
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>aFile
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>aFile.close
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>aFile<nbsp/>=<nbsp/>nil
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>aFile
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<subsection>Blocks Can Be Closures</subsection>
<p/>
Let's get back to our jukebox for a moment (remember the
jukebox?).
At some point we'll be working on the code that handles the 
user interface---the buttons that people press to select songs and
control the jukebox. We'll need to associate actions with those
buttons: press <smallfont>STOP</smallfont> and the music stops. It turns out that
Ruby's blocks are a convenient way to do this. Let's start out by
assuming that the people who made the hardware implemented a Ruby
extension that gives us a basic button
class. (We talk about extending Ruby beginning on page 169.)
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!-  def initialize(label)
!-  end
!-end
bStart = Button.new("Start")
bPause = Button.new("Pause")
# ...
]]></fullcode>
bStart<nbsp/>=<nbsp/>Button.new("Start")
bPause<nbsp/>=<nbsp/>Button.new("Pause")
#<nbsp/>...
</alltt>
</codefragment>
<p/>
What happens when the user presses one of our buttons? In the
<classname>Button</classname> class, the hardware folks rigged things so that a
callback method, <meth>buttonPressed</meth>, will be invoked. 
The obvious way of adding functionality to these buttons is to create
subclasses of <classname>Button</classname> and have each subclass implement its own
<meth>buttonPressed</meth> method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!-  def initialize(label)
!-  end
!-end
class StartButton < Button
  def initialize
    super("Start")       # invoke Button's initialize
  end
  def buttonPressed
    # do start actions...
  end
end

bStart = StartButton.new
]]></fullcode>
class<nbsp/>StartButton<nbsp/>&lt;<nbsp/>Button
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>super("Start")<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>invoke<nbsp/>Button's<nbsp/>initialize
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>buttonPressed
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>do<nbsp/>start<nbsp/>actions...
<nbsp/><nbsp/>end
end
<p/>
bStart<nbsp/>=<nbsp/>StartButton.new
</alltt>
</codefragment>
<p/>
There are two problems here. First, this will lead to a large number
of subclasses. If the interface to <classname>Button</classname> changes, this could
involve us in a lot of maintenance. Second, the actions performed when 
a button is pressed are expressed at the wrong level; they are not a
feature of the button, but are a feature of the jukebox that uses the
buttons. We can fix both of these problems using blocks.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!-  def initialize(label)
!-  end
!-end
!-songList = nil
class JukeboxButton < Button
  def initialize(label, &action)
    super(label)
    @action = action
  end
  def buttonPressed
    @action.call(self)  
  end
end

bStart = JukeboxButton.new("Start") { songList.start }
bPause = JukeboxButton.new("Pause") { songList.pause }
]]></fullcode>
class<nbsp/>JukeboxButton<nbsp/>&lt;<nbsp/>Button
<nbsp/><nbsp/>def<nbsp/>initialize(label,<nbsp/>&amp;action)
<nbsp/><nbsp/><nbsp/><nbsp/>super(label)
<nbsp/><nbsp/><nbsp/><nbsp/>@action<nbsp/>=<nbsp/>action
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>buttonPressed
<nbsp/><nbsp/><nbsp/><nbsp/>@action.call(self)
<nbsp/><nbsp/>end
end
<p/>
bStart<nbsp/>=<nbsp/>JukeboxButton.new("Start")<nbsp/>{<nbsp/>songList.start<nbsp/>}
bPause<nbsp/>=<nbsp/>JukeboxButton.new("Pause")<nbsp/>{<nbsp/>songList.pause<nbsp/>}
</alltt>
</codefragment>
<p/>
The key to all this is the second parameter to
<cim><front>JukeboxButton</front><back>initialize</back></cim>. If the last parameter in a method
definition is prefixed with an ampersand (such as <tt>&amp;action</tt>),
Ruby
looks for a code block whenever that method is called. That code block
is converted to an object of class <classname>Proc</classname> and assigned to the
parameter. You can then treat the parameter as any other variable. In
our example, we assigned it to the instance variable <var>@action</var>.
When the callback method <meth>buttonPressed</meth> is invoked, we use the
<cim><file>proc</file><front>Proc</front><back>call</back><mref>call</mref></cim> method on that object to invoke the block.
<p/>
So what exactly do we have when we create a <classname>Proc</classname> object? The
interesting thing is that it's more than just a chunk of code.
Associated with a block (and hence a <classname>Proc</classname> object) is all the
context in which the block was <em>defined</em>: the value of
<const>self</const>, and the methods, variables, and constants in scope. Part
of the magic of Ruby is that the block can still use all this original
scope information even if the environment in which it was defined
would otherwise have disappeared.  In other languages, this facility
is called a <em>closure</em>.
<p/>
Let's look at a contrived example. This example uses the method
<meth>proc</meth>,
which converts a block to a <classname>Proc</classname> object.
<p/>
<codefragment>
<fullcode><![CDATA[  def nTimes(aThing)
    return proc { |n| aThing * n }
  end

  p1 = nTimes(23)
  p1.call(3)
  p1.call(4)
  p2 = nTimes("Hello ")
  p2.call(3)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>nTimes(aThing)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>return<nbsp/>proc<nbsp/>{<nbsp/>|n|<nbsp/>aThing<nbsp/>*<nbsp/>n<nbsp/>}</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>p1<nbsp/>=<nbsp/>nTimes(23)</tt></td>
</tr>
<tr>
  <td><tt>p1.call(3)</tt></td>
  <td>&#187;</td>
  <td><tt>69</tt></td>
</tr>
<tr>
  <td><tt>p1.call(4)</tt></td>
  <td>&#187;</td>
  <td><tt>92</tt></td>
</tr>
<tr>
<td colspan="3"><tt>p2<nbsp/>=<nbsp/>nTimes("Hello<nbsp/>")</tt></td>
</tr>
<tr>
  <td><tt>p2.call(3)</tt></td>
  <td>&#187;</td>
  <td><tt>"Hello<nbsp/>Hello<nbsp/>Hello<nbsp/>"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The method <meth>nTimes</meth> returns a <classname>Proc</classname> object that references
the method's parameter, <tt>aThing</tt>. Even though that parameter is out 
of scope by the time the block is called, the parameter remains
accessible to the block.
<p/>
</chapter>
</ppdoc>
