<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="Expressions">
<p/>
So far we've been fairly cavalier in our use of expressions in Ruby.
After all, <tt>a=b+c</tt> is pretty standard
stuff.  You could write a whole heap of Ruby code without reading any
of this chapter.
<p/>
But it wouldn't be as much fun <tt>;-)</tt>.
<p/>
One of the first differences with Ruby is that anything that can
reasonably return a value does: just about everything is an
expression. What does this mean in practice?
<p/>
Some obvious things include the ability to chain statements together.
<p/>
<codefragment>
<fullcode><![CDATA[  a = b = c = 0
  [ 3, 1, 7, 0 ].sort.reverse
]]></fullcode><rubycode>
<tr>
  <td><tt>a<nbsp/>=<nbsp/>b<nbsp/>=<nbsp/>c<nbsp/>=<nbsp/>0</tt></td>
  <td>&#187;</td>
  <td><tt>0</tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>3,<nbsp/>1,<nbsp/>7,<nbsp/>0<nbsp/>].sort.reverse</tt></td>
  <td>&#187;</td>
  <td><tt>[7,<nbsp/>3,<nbsp/>1,<nbsp/>0]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Perhaps less obvious, things that are normally statements in C
or Java are expressions in Ruby. For example, the <kw>if</kw> and
<kw>case</kw> statements both return the value of the last expression
executed.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class Song
!-   TradJazz, Jazz, Other = 1, 2, 3
!-   attr :written
!-   def mp3Type() @written = 1; 1 end
!-  end
!-  class Date
!-    def initialize(a,b,c) end
!-    def coerce(i) [1,1] end
!-  end
!-  class Rating
!-    SkipThisOne, CouldDoBetter, Rave = 1, 2, 3
!-  end
!-  class MP3
!-    Jazz = 1
!-  end
!-  song = Song.new
!-  votesCast = 0
  songType = if song.mp3Type == MP3::Jazz
               if song.written < Date.new(1935, 1, 1)
                 Song::TradJazz
               else
                 Song::Jazz
               end
             else
               Song::Other
             end

   rating = case votesCast
            when 0...10    then Rating::SkipThisOne
            when 10...50   then Rating::CouldDoBetter
            else                Rating::Rave
            end
]]></fullcode>
songType<nbsp/>=<nbsp/>if<nbsp/>song.mp3Type<nbsp/>==<nbsp/>MP3::Jazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>song.written<nbsp/>&lt;<nbsp/>Date.new(1935,<nbsp/>1,<nbsp/>1)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::TradJazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::Jazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::Other
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/>rating<nbsp/>=<nbsp/>case<nbsp/>votesCast
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>0...10<nbsp/><nbsp/><nbsp/><nbsp/>then<nbsp/>Rating::SkipThisOne
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>10...50<nbsp/><nbsp/><nbsp/>then<nbsp/>Rating::CouldDoBetter
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Rating::Rave
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
We'll talk more about <kw>if</kw> and <kw>case</kw> starting
on page 79.
<section>Operator Expressions</section>
<p/>
Ruby has the basic set of operators (+, -, *, /, and so on) as well
as a few surprises. A complete list of the operators, and their
precedences, is given in Table 18.4 on page 219.
<p/>
In Ruby, many operators are actually method calls. When you write
<tt>a*b+c</tt>
you're actually asking the object referenced by <var>a</var> to execute the 
method ``<tt>*</tt>'', passing in the parameter <var>b</var>. You then ask the
object that results from that calculation to execute ``<tt>+</tt>'',
passing <var>c</var> as a parameter. This is exactly equivalent
to writing
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  a,b,c=1,2,3
  (a.*(b)).+(c)
]]></fullcode>
(a.*(b)).+(c)
</alltt>
</codefragment>
<p/>
Because everything is an object, and because you can redefine
instance methods, you can always redefine basic arithmetic if you
don't like the answers you're getting.
<p/>
<codefragment>
<fullcode><![CDATA[  class Fixnum
    alias oldPlus +
    def +(other)
      oldPlus(other).succ
    end
  end

  1 + 2
  a = 3
  a += 4
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Fixnum</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>alias<nbsp/>oldPlus<nbsp/>+</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>+(other)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>oldPlus(other).succ</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/>+<nbsp/>2</tt></td>
  <td>&#187;</td>
  <td><tt>4</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>3</tt></td>
</tr>
<tr>
  <td><tt>a<nbsp/>+=<nbsp/>4</tt></td>
  <td>&#187;</td>
  <td><tt>8</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
More useful is the fact that classes that you write can participate in
operator expressions just as if they were built-in objects. For
example, we might want to be able to extract a number of seconds of
music from the middle of a song. We could using the indexing operator
``<tt>[]</tt>'' to specify the music to be extracted.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Song
    def [](fromTime, toTime)
      result = Song.new(self.title + " [extract]",
                        self.artist,
                        toTime - fromTime)
      result.setStartTime(fromTime)
      result
    end
  end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>def<nbsp/>[](fromTime,<nbsp/>toTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>Song.new(self.title<nbsp/>+<nbsp/>"<nbsp/>[extract]",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>self.artist,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>toTime<nbsp/>-<nbsp/>fromTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result.setStartTime(fromTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This code fragment extends class <classname>Song</classname> with the method
``<tt>[]</tt>'', which takes two parameters (a start time and an end
time).  It returns a new song, with the music clipped to the given
interval.  We could then play the introduction to a song with code
such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  aSong[0, 0.15].play
]]></fullcode>
aSong[0,<nbsp/>0.15].play
</alltt>
</codefragment>
<section>Miscellaneous Expressions</section>
<p/>
As well as the obvious operator expressions and method calls, and the
(perhaps) less obvious statement expressions (such as <kw>if</kw> and
<kw>case</kw>), Ruby has a few more things that you can use in
expressions.
<subsection>Command Expansion</subsection>
<p/>
If you enclose a string in backquotes, or use the delimited form
prefixed by <tt>%x</tt>, it will (by default) be executed as a command by
your underlying operating system.
The value of the expression is the
standard output of that command. Newlines will not be stripped, so it is
likely that the value you get back will have a trailing return or
linefeed character. 
<p/>
<codefragment>
<fullcode><![CDATA[ `date`
 `dir`.split[34]
 %x{echo "Hello there"}
]]></fullcode><rubycode>
<tr>
  <td><tt>`date`</tt></td>
  <td>&#187;</td>
  <td><tt>"Sun<nbsp/>Jun<nbsp/><nbsp/>9<nbsp/>00:08:26<nbsp/>CDT<nbsp/>2002\n"</tt></td>
</tr>
<tr>
  <td><tt>`dir`.split[34]</tt></td>
  <td>&#187;</td>
  <td><tt>"lib_singleton.tip"</tt></td>
</tr>
<tr>
  <td><tt>%x{echo<nbsp/>"Hello<nbsp/>there"}</tt></td>
  <td>&#187;</td>
  <td><tt>"Hello<nbsp/>there\n"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can use expression expansion and all the usual escape sequences in
the command string. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  for i in 0..3
    status = `dbmanager status id=#{i}`
    # ...
  end
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>0..3
<nbsp/><nbsp/>status<nbsp/>=<nbsp/>`dbmanager<nbsp/>status<nbsp/>id=#{i}`
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
The exit status of the command is available in the global variable
<var>$?</var>.
<subsubsection>Backquotes Are Soft</subsubsection>
<p/>
In the description of the command output expression, we said that the
string in backquotes would ``by default'' be executed as a command. In 
fact, the string is passed to the method called <mmm><file>kernel</file><front>Kernel</front><back>`</back><mref>_bq</mref></mmm>
(a single backquote). If you want, you can override
this.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  alias oldBackquote `
  def `(cmd)
    result = oldBackquote(cmd)
    if $? != 0
      raise "Command #{cmd} failed"
    end
    result
  end
  print `date`
  print `data`
]]></fullcode>
alias<nbsp/>oldBackquote<nbsp/>`
def<nbsp/>`(cmd)
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>oldBackquote(cmd)
<nbsp/><nbsp/>if<nbsp/>$?<nbsp/>!=<nbsp/>0
<nbsp/><nbsp/><nbsp/><nbsp/>raise<nbsp/>"Command<nbsp/>#{cmd}<nbsp/>failed"
<nbsp/><nbsp/>end
<nbsp/><nbsp/>result
end
print<nbsp/>`date`
print<nbsp/>`data`
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Sun<nbsp/>Jun<nbsp/><nbsp/>9<nbsp/>00:08:26<nbsp/>CDT<nbsp/>2002
prog.rb:3:<nbsp/>command<nbsp/>not<nbsp/>found:<nbsp/>data
prog.rb:5:in<nbsp/>``':<nbsp/>Command<nbsp/>data<nbsp/>failed<nbsp/>(RuntimeError)
	from<nbsp/>prog.rb:10
</alltt>
</codefragment>
<section>Assignment</section>
<p/>
Just about every example we've given so far in this book has featured
assignment. Perhaps it's about time we said something about it.
<p/>
An assignment statement sets the variable or attribute on its left
side (the <em>lvalue</em>) to refer to the value on the right (the
<em>rvalue</em>).
It then returns that value as the result of the
assignment expression.  This means that you can chain assignments and
that you can
perform assignments in some unexpected places.
<p/>
<codefragment>
<fullcode><![CDATA[!-$stdin = DATA
  a = b = 1 + 2 + 3
  a
  b
  a = (b = 1 + 2) + 3
  a
  b
  File.open(name = gets.chomp)
!-__END__
!-testfile
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>b<nbsp/>=<nbsp/>1<nbsp/>+<nbsp/>2<nbsp/>+<nbsp/>3</tt></td>
</tr>
<tr>
  <td><tt>a</tt></td>
  <td>&#187;</td>
  <td><tt>6</tt></td>
</tr>
<tr>
  <td><tt>b</tt></td>
  <td>&#187;</td>
  <td><tt>6</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>(b<nbsp/>=<nbsp/>1<nbsp/>+<nbsp/>2)<nbsp/>+<nbsp/>3</tt></td>
</tr>
<tr>
  <td><tt>a</tt></td>
  <td>&#187;</td>
  <td><tt>6</tt></td>
</tr>
<tr>
  <td><tt>b</tt></td>
  <td>&#187;</td>
  <td><tt>3</tt></td>
</tr>
<tr>
<td colspan="3"><tt>File.open(name<nbsp/>=<nbsp/>gets.chomp)</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
There are two basic forms of assignment in Ruby. The first assigns an
object reference to a variable or constant.  This form of assignment
is hard-wired into the language.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  instrument = "piano"
  MIDDLE_A   = 440
]]></fullcode>
instrument<nbsp/>=<nbsp/>"piano"
MIDDLE_A<nbsp/><nbsp/><nbsp/>=<nbsp/>440
</alltt>
</codefragment>
<p/>
The second form of assignment involves having an object attribute or
element reference on the left-hand side. 
<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
!-instrument = "piano"
!-aSong = Song.new(1,2,3)
  aSong.duration    = 234
  instrument["ano"] = "ccolo"
]]></fullcode>
aSong.duration<nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>234
instrument["ano"]<nbsp/>=<nbsp/>"ccolo"
</alltt>
</codefragment>
<p/>
These forms are special, because they are implemented by calling
methods in the lvalues, which means you can override them.
<p/>
We've already seen how to define a writable object attribute. Simply
define a method name ending in an equals sign. This method receives as 
its parameter the assignment's rvalue.
<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/>def<nbsp/>duration=(newDuration)
<nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>newDuration
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
There is no reason that these attribute setting methods must
correspond with internal instance variables, or that there has to be
an attribute reader for every attribute writer (or vice versa).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Amplifier
    def volume=(newVolume)
      self.leftChannel = self.rightChannel = newVolume
    end
    # ...
  end
]]></fullcode>
class<nbsp/>Amplifier
<nbsp/><nbsp/>def<nbsp/>volume=(newVolume)
<nbsp/><nbsp/><nbsp/><nbsp/>self.leftChannel<nbsp/>=<nbsp/>self.rightChannel<nbsp/>=<nbsp/>newVolume
<nbsp/><nbsp/>end
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
<sidebar name="Using Accessors Within a Class">
<p/>
  Why did we write <tt>self.leftChannel</tt> in the example on page
  74? Well, there's a hidden gotcha with writable
  attributes. Normally, methods within a class can invoke other
  methods in the same class and its superclasses in functional form
  (that is, with an implicit receiver of <tt>self</tt>). However, this
  doesn't work with attribute writers. Ruby sees the assignment and
  decides that the name on the left must be a local variable, not a
  method call to an attribute writer.    
<codefragment>
<fullcode><![CDATA[  class BrokenAmplifier
    attr_accessor :leftChannel, :rightChannel
    def volume=(vol)
      leftChannel = self.rightChannel = vol
    end
  end

  ba = BrokenAmplifier.new
  ba.leftChannel = ba.rightChannel = 99
  ba.volume = 5
  ba.leftChannel
  ba.rightChannel
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>BrokenAmplifier</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>attr_accessor<nbsp/>:leftChannel,<nbsp/>:rightChannel</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>volume=(vol)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>leftChannel<nbsp/>=<nbsp/>self.rightChannel<nbsp/>=<nbsp/>vol</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>ba<nbsp/>=<nbsp/>BrokenAmplifier.new</tt></td>
</tr>
<tr>
<td colspan="3"><tt>ba.leftChannel<nbsp/>=<nbsp/>ba.rightChannel<nbsp/>=<nbsp/>99</tt></td>
</tr>
<tr>
<td colspan="3"><tt>ba.volume<nbsp/>=<nbsp/>5</tt></td>
</tr>
<tr>
  <td><tt>ba.leftChannel</tt></td>
  <td>&#187;</td>
  <td><tt>99</tt></td>
</tr>
<tr>
  <td><tt>ba.rightChannel</tt></td>
  <td>&#187;</td>
  <td><tt>5</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
We forgot to put ``<tt>self.</tt>'' in front of the assignment to
<tt>leftChannel</tt>, so Ruby stored the new value in a local variable of
method <meth>volume=</meth>; the object's attribute never got updated.
This can be a tricky bug to track down.
<p/>
</sidebar>
<subsection>Parallel Assignment</subsection>
<p/>
During your first week in a programming course (or the second semester
if it was a party school), you may have had to write code to swap the
values in two variables:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[int a = 1;
int b = 2;
int temp;

temp = a;
a = b;
b = temp;
]]></fullcode>
int<nbsp/>a<nbsp/>=<nbsp/>1;
int<nbsp/>b<nbsp/>=<nbsp/>2;
int<nbsp/>temp;
<p/>
temp<nbsp/>=<nbsp/>a;
a<nbsp/>=<nbsp/>b;
b<nbsp/>=<nbsp/>temp;
</alltt>
</codefragment>
<p/>
You can do this much more cleanly in Ruby:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  a, b = 1, 2
  a, b = b, a
]]></fullcode>
a,<nbsp/>b<nbsp/>=<nbsp/>b,<nbsp/>a
</alltt>
</codefragment>
<p/>
Ruby assignments are effectively performed in parallel, so the values
assigned are not affected by the assignment itself.  The values on the
right-hand side are evaluated in the order in which they appear before any
assignment is made to variables or attributes on the left. A somewhat
contrived example illustrates this. The second line assigns to the
variables <tt>a</tt>, <tt>b</tt>, and <tt>c</tt> the values of the expressions
<tt>x</tt>, <tt>x+=1</tt>, and <tt>x+=1</tt>, respectively.
<p/>
<codefragment>
<fullcode><![CDATA[  x = 0
  a, b, c   =   x, (x += 1), (x += 1)
]]></fullcode><rubycode>
<tr>
  <td><tt>x<nbsp/>=<nbsp/>0</tt></td>
  <td>&#187;</td>
  <td><tt>0</tt></td>
</tr>
<tr>
  <td><tt>a,<nbsp/>b,<nbsp/>c<nbsp/><nbsp/><nbsp/>=<nbsp/><nbsp/><nbsp/>x,<nbsp/>(x<nbsp/>+=<nbsp/>1),<nbsp/>(x<nbsp/>+=<nbsp/>1)</tt></td>
  <td>&#187;</td>
  <td><tt>[0,<nbsp/>1,<nbsp/>2]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
When an assignment has more than one lvalue, the assignment expression
returns an array of the rvalues.
If an assignment contains more lvalues than rvalues, the excess
lvalues are
set to <tt>nil</tt>. If a multiple assignment contains more rvalues than
lvalues, the extra rvalues are ignored. As of Ruby 1.6.2, if an
assignment has one lvalue and multiple rvalues, the rvalues are
converted to an array and assigned to the lvalue.
<p/>
You can collapse and expand arrays using Ruby's parallel assignment
operator.  If the last lvalue is preceded by an asterisk, all the
remaining rvalues will be collected and assigned to that lvalue as an
array. Similarly, if the last rvalue is an array, you can prefix it
with an asterisk, which effectively expands it into its constituent
values in place.  (This is not necessary if the rvalue is the only
thing on the right-hand side---the array will be expanded
automatically.)
<p/>
<codefragment>
  <table>
<tr>
<td colspan="4"><tt>a = [1, 2, 3, 4]</tt></td>
</tr>
<tr>
  <td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>a</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2</td>
</tr>
<tr>
  <td>b,<nbsp/>*c<nbsp/>=<nbsp/>a</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == [2, 3, 4]</td>
</tr>
<tr>
  <td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>99,<nbsp/><nbsp/>a</td>
  <td> &#187;</td>
  <td>b == 99,</td>
  <td>c == [1, 2, 3, 4]</td>
</tr>
<tr>
  <td>b,<nbsp/>*c<nbsp/>=<nbsp/>99,<nbsp/><nbsp/>a</td>
  <td> &#187;</td>
  <td>b == 99,</td>
  <td>c == [[1, 2, 3, 4]]</td>
</tr>
<tr>
  <td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>99,<nbsp/>*a</td>
  <td> &#187;</td>
  <td>b == 99,</td>
  <td>c == 1</td>
</tr>
<tr>
  <td>b,<nbsp/>*c<nbsp/>=<nbsp/>99,<nbsp/>*a</td>
  <td> &#187;</td>
  <td>b == 99,</td>
  <td>c == [1, 2, 3, 4]</td>
</tr>
</table>
<p/>
</codefragment>
<subsubsection>Nested Assignments</subsubsection>
<p/>
Parallel assignments have one more feature worth mentioning.
The left-hand side of an assignment may contain a parenthesized list of
terms. Ruby treats these terms as if they were a nested assignment
statement. It extracts out the corresponding rvalue, assigning it to
the parenthesized terms, before continuing with the higher-level
assignment.
<p/>
<codefragment>
  <table>
<tr>
  <td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,2,3,4</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2,</td>
  <td>d == nil,</td>
  <td>e == 3</td>
</tr>
<tr>
  <td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>[1,2,3,4]</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2,</td>
  <td>d == nil,</td>
  <td>e == 3</td>
</tr>
<tr>
  <td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3],4</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2,</td>
  <td>d == 3,</td>
  <td>e == 4</td>
</tr>
<tr>
  <td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3,4],5</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2,</td>
  <td>d == 3,</td>
  <td>e == 5</td>
</tr>
<tr>
  <td>b,<nbsp/>(c,*d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3,4],5</td>
  <td> &#187;</td>
  <td>b == 1,</td>
  <td>c == 2,</td>
  <td>d == [3, 4],</td>
  <td>e == 5</td>
</tr>
</table>
<p/>
</codefragment>
<subsection>Other Forms of Assignment</subsection>
<p/>
In common with many other languages, Ruby has a syntactic shortcut:
<tt>a=a+2</tt> may be written as <tt>a+=2</tt>.
<p/>
The second form is converted internally to the first. This means that
operators that you have defined as methods in your own classes work as
you'd expect.
<p/>
<codefragment>
<fullcode><![CDATA[  class Bowdlerize
    def initialize(aString)
      @value = aString.gsub(/[aeiou]/, '*')
    end
    def +(other)
      Bowdlerize.new(self.to_s + other.to_s)
    end
    def to_s
      @value
    end
!-    def inspect
!-      @value
!-    end
  end

  a = Bowdlerize.new("damn ")
  a += "shame"
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Bowdlerize</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>initialize(aString)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@value<nbsp/>=<nbsp/>aString.gsub(/[aeiou]/,<nbsp/>'*')</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>+(other)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>Bowdlerize.new(self.to_s<nbsp/>+<nbsp/>other.to_s)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@value</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>a<nbsp/>=<nbsp/>Bowdlerize.new("damn<nbsp/>")</tt></td>
  <td>&#187;</td>
  <td><tt>d*mn</tt></td>
</tr>
<tr>
  <td><tt>a<nbsp/>+=<nbsp/>"shame"</tt></td>
  <td>&#187;</td>
  <td><tt>d*mn<nbsp/>sh*m*</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Conditional Execution</section>
<p/>
Ruby has several different mechanisms for conditional execution of
code; most of them should feel familiar, and many have some neat
twists. Before we get into them, though, we need to spend a short time 
looking at boolean expressions.
<subsection>Boolean Expressions</subsection>
<p/>
Ruby has a simple definition of truth. Any value that is not <tt>nil</tt> or
the constant <const>false</const> is true. You'll find that the library
routines use this fact consistently. For example, <cim><file>io</file><front>IO</front><back>gets</back><mref>gets</mref></cim>,
which returns the next line from a file, returns <tt>nil</tt> at end of
file, enabling you to write loops such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  while line = gets
    # process line
  end
]]></fullcode>
while<nbsp/>line<nbsp/>=<nbsp/>gets
<nbsp/><nbsp/>#<nbsp/>process<nbsp/>line
end
</alltt>
</codefragment>
<p/>
However, there's a trap here for C, C++, and Perl
programmers. The number zero is <em>not</em> interpreted as a false
value. Neither is a zero-length string. This can be a tough habit to
break.
<subsubsection>Defined?, And, Or, and Not</subsubsection>
<p/>
Ruby supports all the standard boolean operators and introduces the
new operator <tt>defined?</tt>.
<p/>
Both ``<tt>and</tt>'' and ``<tt>&amp;&amp;</tt>''
evaluate to true only if both operands are
true. They evaluate the second operand only if the first is true
(this is sometimes known as ``short-circuit evaluation'').  The only
difference in the two forms is precedence (``<tt>and</tt>'' binds lower than
``<tt>&amp;&amp;</tt>'').
<p/>
Similarly, both ``<tt>or</tt>'' and ``<tt>||</tt>''
evaluate to true if either operand
is true.  They evaluate their second operand only if the first is
false.  As with ``<tt>and</tt>'', the only difference between ``<tt>or</tt>'' and
``<tt>||</tt>'' is their precedence.
<p/>
Just to make life interesting, ``<tt>and</tt>'' and ``<tt>or</tt>'' have the
same precedence, while ``<tt>&amp;&amp;</tt>'' has a higher precedence than
``<tt>||</tt>''.
<p/>
``<tt>not</tt>'' and ``<tt>!</tt>''
return the opposite of their operand (false if the
operand is true, and true if the operand is false). And, yes, ``<tt>not</tt>''
and ``<tt>!</tt>'' differ only in precedence.
<p/>
All these precedence rules are summarized in Table
18.4 on page 219.
<p/>
The <tt>defined?</tt>
operator returns <tt>nil</tt> if its argument (which can be
an arbitrary expression) is not defined, otherwise it returns a
description of that argument. If the argument is <kw>yield</kw>,
<tt>defined?</tt> returns the string ``yield'' if a code block is
associated with the current context.
<p/>
<codefragment>
<fullcode><![CDATA[  defined? 1
  defined? dummy
  defined? printf
  defined? String
  defined? $&
  defined? $_
  defined? Math::PI
  defined? ( c,d = 1,2 )
  defined? 42.abs
]]></fullcode><rubycode>
<tr>
  <td><tt>defined?<nbsp/>1</tt></td>
  <td>&#187;</td>
  <td><tt>"expression"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>dummy</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>printf</tt></td>
  <td>&#187;</td>
  <td><tt>"method"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>String</tt></td>
  <td>&#187;</td>
  <td><tt>"constant"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>$&amp;</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>$_</tt></td>
  <td>&#187;</td>
  <td><tt>"global-variable"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>Math::PI</tt></td>
  <td>&#187;</td>
  <td><tt>"constant"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>(<nbsp/>c,d<nbsp/>=<nbsp/>1,2<nbsp/>)</tt></td>
  <td>&#187;</td>
  <td><tt>"assignment"</tt></td>
</tr>
<tr>
  <td><tt>defined?<nbsp/>42.abs</tt></td>
  <td>&#187;</td>
  <td><tt>"method"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
In addition to the boolean operators, Ruby objects support comparison
using the methods <tt>==</tt>, <tt>===</tt>, <tt>&lt;=&gt;</tt>, <tt>=~</tt>, <tt>eql?</tt>,
and <tt>equal?</tt> (see Table 7.1 on page 79). All but <tt>&lt;=&gt;</tt>
are defined in class <classname>Object</classname> but are often overridden by
descendents to provide appropriate semantics. For example, class
<classname>Array</classname> redefines <tt>==</tt> so that two array objects are equal if
they have the same number of elements and corresponding elements are
equal.
<p/>
<figure type="table">
  <caption>Common comparison operators</caption>            
  <table>
<th>
  <td><b>Operator</b></td>
  <td><b>Meaning</b></td>
</th>
<tr>
  <td><tt>==</tt></td>
  <td>Test for equal value.</td>
</tr>
<tr>
  <td><tt>===</tt></td>
  <td>Used to test equality within a <kw>when</kw> clause of a
                <kw>case</kw> statement.</td>
</tr>
<tr>
  <td><tt>&lt;=&gt;</tt></td>
  <td>General comparison operator. Returns -1, 0, or +1,
                depending on whether its receiver is less than, equal to, or
                greater than its argument.</td>
</tr>
<tr>
  <td><tt>&lt;</tt>, <tt>&lt;=</tt>, <tt>&gt;=</tt>, <tt>&gt;</tt></td>
  <td>Comparison operators for less than, less than or
                equal, greater than or equal, and greater than.</td>
</tr>
<tr>
  <td><tt>=~</tt></td>
  <td>Regular expression pattern match.</td>
</tr>
<tr>
  <td><tt>eql?</tt></td>
  <td>True if the receiver and argument have both the same
                type and equal values. 1 == 1.0 returns <const>true</const>, 
                but 1.eql?(1.0) is <const>false</const>.</td>
</tr>
<tr>
  <td><tt>equal?</tt></td>
  <td>True if the receiver and argument have the same
                object id.</td>
</tr>
<bottomrule/></table>
<p/>
</figure>
<p/>
Both <tt>==</tt> and <tt>=~</tt> have negated forms, <tt>!=</tt> and <tt>!~</tt>.
However, these are converted by Ruby when your program is read.
<tt>a!=b</tt> is equivalent to <tt>!(a==b)</tt>,
and <tt>a!~b</tt> is the
same as <tt>!(a=~b)</tt>.  This means that if you write a class that
overrides <tt>==</tt> or <tt>=~</tt> you get a working <tt>!=</tt> and <tt>!~</tt>
for free. But on the flip side, this also means that you cannot define 
<tt>!=</tt> and <tt>!~</tt> independent of <tt>==</tt> and <tt>=~</tt>, respectively.
<p/>
You can use a Ruby range as a boolean expression.
A
range such as <tt>exp1..exp2</tt> will evaluate as false
until <tt>exp1</tt> becomes true. The range will then evaluate as true
until <tt>exp2</tt> becomes true. Once this happens, the range resets,
ready to fire again. We show some examples of this
on page 82. 
<p/>
Finally, you can use a bare regular expression as a boolean
expression. Ruby expands it to <tt>$_=~/re/</tt>.
<subsection>If and Unless Expressions</subsection>
<p/>
An <kw>if</kw> expression in Ruby is pretty similar to ``if'' statements
in other languages.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie" then
  handle = "Dizzy"
elsif aSong.artist == "Parker" then
  handle = "Bird"
else
  handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
If you lay out your <kw>if</kw> statements on multiple lines, you can
leave off the <kw>then</kw> keyword.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie"
  handle = "Dizzy"
elsif aSong.artist == "Parker"
  handle = "Bird"
else
  handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
However, if you lay your code out more tightly, the <kw>then</kw> keyword
is necessary to separate the boolean expression from the following
statements.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie" then  handle = "Dizzy"
elsif aSong.artist == "Parker" then  handle = "Bird"
else  handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
You can have zero or more <tt>elsif</tt> clauses and an optional
<tt>else</tt> clause.
<p/>
As we've said before, <tt>if</tt> is
an expression, not a statement---it returns a value.  You don't have
to use the value of an <tt>if</tt> expression, but it can come in handy.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
handle = if aSong.artist == "Gillespie" then
           "Dizzy"
         elsif aSong.artist == "Parker" then
           "Bird"
         else
           "unknown"
         end
]]></fullcode>
handle<nbsp/>=<nbsp/>if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Dizzy"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Bird"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"unknown"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
Ruby also has a negated form of the <tt>if</tt> statement:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.duration() 1 end
unless aSong.duration > 180 then
  cost = .25
else
  cost = .35
end
]]></fullcode>
unless<nbsp/>aSong.duration<nbsp/>&gt;<nbsp/>180<nbsp/>then
<nbsp/><nbsp/>cost<nbsp/>=<nbsp/>.25
else
<nbsp/><nbsp/>cost<nbsp/>=<nbsp/>.35
end
</alltt>
</codefragment>
<p/>
Finally, for the C fans out there, Ruby also supports the C-style
conditional expression:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.duration() 1 end
cost = aSong.duration > 180 ? .35 : .25
]]></fullcode>
cost<nbsp/>=<nbsp/>aSong.duration<nbsp/>&gt;<nbsp/>180<nbsp/>?<nbsp/>.35<nbsp/>:<nbsp/>.25
</alltt>
</codefragment>
<p/>
The conditional expression returns the value of either the expression
before or the expression after the colon, depending on whether the
boolean expression before the question mark evaluates to <const>true</const>
or <const>false</const>. In this case, if the song duration is greater than 3 
minutes, the expression returns .35. For shorter songs, it returns
.25. Whatever the result, it is then assigned to <var>cost</var>.
<subsubsection>If and Unless Modifiers</subsubsection>
<p/>
Ruby shares a neat feature with Perl. Statement modifiers let you tack
conditional statements onto the end of a normal statement.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-fDebug = false; total = 0
  mon, day, year = $1, $2, $3 if /(\d\d)-(\d\d)-(\d\d)/
  puts "a = #{a}" if fDebug
  print total unless total == 0
]]></fullcode>
mon,<nbsp/>day,<nbsp/>year<nbsp/>=<nbsp/>$1,<nbsp/>$2,<nbsp/>$3<nbsp/>if<nbsp/>/(\d\d)-(\d\d)-(\d\d)/
puts<nbsp/>"a<nbsp/>=<nbsp/>#{a}"<nbsp/>if<nbsp/>fDebug
print<nbsp/>total<nbsp/>unless<nbsp/>total<nbsp/>==<nbsp/>0
</alltt>
</codefragment>
<p/>
For an <kw>if</kw> modifier, the preceding expression will be evaluated only
if the condition is true. <kw>unless</kw> works the other way around.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  while gets
    next if /^#/            # Skip comments
    parseLine unless /^$/   # Don't parse empty lines
  end
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>/^#/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Skip<nbsp/>comments
<nbsp/><nbsp/>parseLine<nbsp/>unless<nbsp/>/^$/<nbsp/><nbsp/><nbsp/>#<nbsp/>Don't<nbsp/>parse<nbsp/>empty<nbsp/>lines
end
</alltt>
</codefragment>
<p/>
Because <kw>if</kw> itself is an expression, you can get really obscure
with statements such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  artist = "John Coltrane"
!-  nicknames = "yes"
  if artist == "John Coltrane"
    artist = "'Trane"
  end unless nicknames == "no"
]]></fullcode>
if<nbsp/>artist<nbsp/>==<nbsp/>"John<nbsp/>Coltrane"
<nbsp/><nbsp/>artist<nbsp/>=<nbsp/>"'Trane"
end<nbsp/>unless<nbsp/>nicknames<nbsp/>==<nbsp/>"no"
</alltt>
</codefragment>
<p/>
This path leads to the gates of madness.
<section>Case Expressions</section>
<p/>
The Ruby <tt>case</tt> expression is a powerful beast: a multiway <tt>if</tt>
on steroids.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-inputLine = "quit"
case inputLine

  when "debug"
    dumpDebugInfo
    dumpSymbols
    
  when /p\s+(\w+)/
    dumpVariable($1)
    
  when "quit", "exit"
    exit
    
  else
    print "Illegal command: #{inputLine}"
end
]]></fullcode>
case<nbsp/>inputLine
<p/>
<nbsp/><nbsp/>when<nbsp/>"debug"
<nbsp/><nbsp/><nbsp/><nbsp/>dumpDebugInfo
<nbsp/><nbsp/><nbsp/><nbsp/>dumpSymbols
<p/>
<nbsp/><nbsp/>when<nbsp/>/p\s+(\w+)/
<nbsp/><nbsp/><nbsp/><nbsp/>dumpVariable($1)
<p/>
<nbsp/><nbsp/>when<nbsp/>"quit",<nbsp/>"exit"
<nbsp/><nbsp/><nbsp/><nbsp/>exit
<p/>
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>print<nbsp/>"Illegal<nbsp/>command:<nbsp/>#{inputLine}"
end
</alltt>
</codefragment>
<p/>
As with <tt>if</tt>, <kw>case</kw> returns the value of the last expression
executed, and you also need a <kw>then</kw> keyword if the
expression is on the same line as the condition.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    year = 1937
  kind = case year
           when 1850..1889 then "Blues"
           when 1890..1909 then "Ragtime"
           when 1910..1929 then "New Orleans Jazz"
           when 1930..1939 then "Swing"
           when 1940..1950 then "Bebop"
           else                 "Jazz"
         end
]]></fullcode>
kind<nbsp/>=<nbsp/>case<nbsp/>year
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1850..1889<nbsp/>then<nbsp/>"Blues"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1890..1909<nbsp/>then<nbsp/>"Ragtime"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1910..1929<nbsp/>then<nbsp/>"New<nbsp/>Orleans<nbsp/>Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1930..1939<nbsp/>then<nbsp/>"Swing"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1940..1950<nbsp/>then<nbsp/>"Bebop"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
<tt>case</tt> operates by comparing the target (the expression after the
keyword <kw>case</kw>) with each of the comparison expressions after the
<kw>when</kw> keywords.  This test is done using
<em>comparison</em><nbsp/><tt>===</tt><nbsp/><em>target</em>. 
As long as a class defines
meaningful semantics for <tt>===</tt> (and all the built-in classes do),
objects of that class can be used in case expressions.
<p/>
For example, regular expressions define <tt>===</tt> as a simple pattern match.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  case line
    when /title=(.*)/
      puts "Title is #$1"
    when /track=(.*)/
      puts "Track is #$1"
    when /artist=(.*)/
      puts "Artist is #$1"
  end
]]></fullcode>
case<nbsp/>line
<nbsp/><nbsp/>when<nbsp/>/title=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Title<nbsp/>is<nbsp/>#$1"
<nbsp/><nbsp/>when<nbsp/>/track=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Track<nbsp/>is<nbsp/>#$1"
<nbsp/><nbsp/>when<nbsp/>/artist=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Artist<nbsp/>is<nbsp/>#$1"
end
</alltt>
</codefragment>
<p/>
Ruby classes are instances of class <classname>Class</classname>, which defines <tt>===</tt>
as a test to see if the argument is an instance of the class or one of
its superclasses. So (abandoning the benefits of polymorphism and
bringing the gods of refactoring down around your ears), you can test
the class of objects:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    class Square; end
!-    class Rectangle; end
!-    class Circle; end
!-    class Triangle; end
!-    shape = Object.new
  case shape
    when Square, Rectangle
      # ...
    when Circle
      # ...
    when Triangle
      # ...
    else
      # ...
  end
]]></fullcode>
case<nbsp/>shape
<nbsp/><nbsp/>when<nbsp/>Square,<nbsp/>Rectangle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>when<nbsp/>Circle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>when<nbsp/>Triangle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<section>Loops</section>
<p/>
Don't tell anyone, but Ruby has pretty primitive built-in looping
constructs.
<p/>
The <kw>while</kw> loop executes its body zero or more times as long as
its condition is true. For example, this common idiom reads until
the input is exhausted.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  while gets
    # ...
  end
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
There's also a negated form that executes the body until the
condition becomes true.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-playList = ""
!-def playList.duration() 100 end
until playList.duration > 60
  playList.add(songList.pop)
end
]]></fullcode>
until<nbsp/>playList.duration<nbsp/>&gt;<nbsp/>60
<nbsp/><nbsp/>playList.add(songList.pop)
end
</alltt>
</codefragment>
<p/>
As with <kw>if</kw> and <kw>unless</kw>, both of the loops can also be used
as statement modifiers.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    a = 1
  a *= 2 while a < 100
  a -= 10 until a < 100
]]></fullcode>
a<nbsp/>*=<nbsp/>2<nbsp/>while<nbsp/>a<nbsp/>&lt;<nbsp/>100
a<nbsp/>-=<nbsp/>10<nbsp/>until<nbsp/>a<nbsp/>&lt;<nbsp/>100
</alltt>
</codefragment>
<p/>
On page 78 in the section on boolean
expressions,
we said that a range can be used as a kind of flip-flop, returning true
when some event happens and then staying true until a second event occurs.
This facility is normally used within loops. In the example that
follows, we read a text file containing the first ten ordinal numbers
(``first,'' ``second,'' and so on)
but only print the lines starting with the one that matches
``third'' and ending with the one that matches ``fifth.''
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  file = File.open("ordinal")
  while file.gets
    print  if /third/ .. /fifth/
  end
]]></fullcode>
file<nbsp/>=<nbsp/>File.open("ordinal")
while<nbsp/>file.gets
<nbsp/><nbsp/>print<nbsp/><nbsp/>if<nbsp/>/third/<nbsp/>..<nbsp/>/fifth/
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
third
fourth
fifth
</alltt>
</codefragment>
<p/>
The elements of a range used in a boolean expression can themselves be
expressions. These are evaluated each time the overall boolean
expression is evaluated. For example, the following code uses the fact 
that the variable <var>$.</var> contains the current input line number to 
display line numbers one through three and those between a match of
<tt>/eig/</tt> and <tt>/nin/</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  file = File.open("ordinal")
  while file.gets
    print if ($. == 1) || /eig/ .. ($. == 3) || /nin/
  end
]]></fullcode>
file<nbsp/>=<nbsp/>File.open("ordinal")
while<nbsp/>file.gets
<nbsp/><nbsp/>print<nbsp/>if<nbsp/>($.<nbsp/>==<nbsp/>1)<nbsp/>||<nbsp/>/eig/<nbsp/>..<nbsp/>($.<nbsp/>==<nbsp/>3)<nbsp/>||<nbsp/>/nin/
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
first
second
third
eighth
ninth
</alltt>
</codefragment>
<p/>
There's one wrinkle when <kw>while</kw> and <kw>until</kw> are used as statement
modifiers. If the statement they are modifying is a
<kw>begin</kw>/<kw>end</kw> block,
the code in the block will always execute
at least one time, regardless of the value of the boolean expression.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  print "Hello\n" while false
  begin
    print "Goodbye\n"
  end while false
]]></fullcode>
print<nbsp/>"Hello\n"<nbsp/>while<nbsp/>false
begin
<nbsp/><nbsp/>print<nbsp/>"Goodbye\n"
end<nbsp/>while<nbsp/>false
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Goodbye
</alltt>
</codefragment>
<subsection>Iterators</subsection>
<p/>
If you read the beginning of the previous section, you might have been
discouraged. ``Ruby has pretty primitive built-in looping
constructs,'' it said. Don't despair, gentle reader, for there's good
news. Ruby doesn't need any sophisticated built-in loops, because all
the fun stuff is implemented using Ruby iterators.
<p/>
For example, Ruby doesn't have a ``for'' loop---at least not the kind
you'd find in C, C++, and Java. Instead, Ruby uses methods defined in
various built-in classes to provide equivalent, but less error-prone,
functionality.
<p/>
Let's look at some examples.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  3.times do
    print "Ho! "
  end
!-    puts
]]></fullcode>
3.times<nbsp/>do
<nbsp/><nbsp/>print<nbsp/>"Ho!<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Ho!<nbsp/>Ho!<nbsp/>Ho!
</alltt>
</codefragment>
<p/>
It's easy to avoid fencepost and off-by-1 errors; this loop will
execute three times, period.  In addition to <meth>times</meth>, integers
can loop over specific ranges by calling <meth>downto</meth>,
<meth>upto</meth>, and <meth>step</meth>. For instance, a traditional ``for''
loop that runs from 0 to 9 (something like <tt>i=0; i &lt; 10; i++</tt>)
is written as follows.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  0.upto(9) do |x|
    print x, " "
  end
!-    puts
]]></fullcode>
0.upto(9)<nbsp/>do<nbsp/>|x|
<nbsp/><nbsp/>print<nbsp/>x,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>4<nbsp/>5<nbsp/>6<nbsp/>7<nbsp/>8<nbsp/>9
</alltt>
</codefragment>
<p/>
A loop from 0 to 12 by 3 can be written as follows.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  0.step(12, 3) {|x| print x, " " }
!-    puts
]]></fullcode>
0.step(12,<nbsp/>3)<nbsp/>{|x|<nbsp/>print<nbsp/>x,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>3<nbsp/>6<nbsp/>9<nbsp/>12
</alltt>
</codefragment>
<p/>
Similarly, iterating over arrays and other containers is made easy
using their <meth>each</meth> method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  [ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
!-    puts
]]></fullcode>
[<nbsp/>1,<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>5<nbsp/>].each<nbsp/>{|val|<nbsp/>print<nbsp/>val,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>5
</alltt>
</codefragment>
<p/>
And once a class supports <meth>each</meth>, the additional methods in the
<modulename>Enumerable</modulename> module (documented beginning on page 403
and summarized on pages 102--103)
become available. For example, the <classname>File</classname> class provides an
<meth>each</meth> method, which returns each line of a file in turn. Using
the <meth>grep</meth> method in <modulename>Enumerable</modulename>, we could iterate over only
those lines that meet a certain condition.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  File.open("ordinal").grep /d$/ do |line|
    print line
  end
]]></fullcode>
File.open("ordinal").grep<nbsp/>/d$/<nbsp/>do<nbsp/>|line|
<nbsp/><nbsp/>print<nbsp/>line
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
second
third
</alltt>
</codefragment>
<p/>
Last, and probably least, is the most basic loop of all. Ruby provides 
a built-in iterator called <meth>loop</meth>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[loop {
  # block ...
}
]]></fullcode>
loop<nbsp/>{
<nbsp/><nbsp/>#<nbsp/>block<nbsp/>...
}
</alltt>
</codefragment>
<p/>
The <meth>loop</meth> iterator calls the associated block forever (or at
least until you break out of the loop, but you'll have to read ahead
to find out how to do that).
<subsection>For ... In</subsection>
<p/>
Earlier we said that the only built-in Ruby looping primitives were
<kw>while</kw> and <kw>until</kw>. What's this ``<kw>for</kw>'' thing, then?
Well, <kw>for</kw> is almost a lump of syntactic sugar. When you write
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-songList = ""
!-def songList.each() end
for aSong in songList
  aSong.play
end
]]></fullcode>
for<nbsp/>aSong<nbsp/>in<nbsp/>songList
<nbsp/><nbsp/>aSong.play
end
</alltt>
</codefragment>
<p/>
Ruby translates it into something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-songList = ""
!-def songList.each() end
  songList.each do |aSong|
    aSong.play
  end
]]></fullcode>
songList.each<nbsp/>do<nbsp/>|aSong|
<nbsp/><nbsp/>aSong.play
end
</alltt>
</codefragment>
<p/>
The only difference between the <kw>for</kw> loop and the <meth>each</meth>
form is the scope of local variables that are defined in the body.
This is discussed on page 87.
<p/>
You can use <kw>for</kw>
to iterate over any object that responds to the method <tt>each</tt>, such
as an <classname>Array</classname> or a <classname>Range</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  for i in ['fee', 'fi', 'fo', 'fum']
    print i, " "
  end
  for i in 1..3
    print i, " "
  end
  for i in File.open("ordinal").find_all { |l| l =~ /d$/}
    print i.chomp, " "
  end
!-puts
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>['fee',<nbsp/>'fi',<nbsp/>'fo',<nbsp/>'fum']
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
end
for<nbsp/>i<nbsp/>in<nbsp/>1..3
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
end
for<nbsp/>i<nbsp/>in<nbsp/>File.open("ordinal").find_all<nbsp/>{<nbsp/>|l|<nbsp/>l<nbsp/>=~<nbsp/>/d$/}
<nbsp/><nbsp/>print<nbsp/>i.chomp,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
fee<nbsp/>fi<nbsp/>fo<nbsp/>fum<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>second<nbsp/>third
</alltt>
</codefragment>
<p/>
As long as your class defines a sensible <tt>each</tt> method, you can use 
a <tt>for</tt> loop to traverse it.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Periods
    def each
      yield "Classical"
      yield "Jazz"
      yield "Rock"
    end
  end

  periods = Periods.new
  for genre in periods
    print genre, " "
  end
!-puts
]]></fullcode>
class<nbsp/>Periods
<nbsp/><nbsp/>def<nbsp/>each
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Classical"
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Rock"
<nbsp/><nbsp/>end
end
<p/>
periods<nbsp/>=<nbsp/>Periods.new
for<nbsp/>genre<nbsp/>in<nbsp/>periods
<nbsp/><nbsp/>print<nbsp/>genre,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Classical<nbsp/>Jazz<nbsp/>Rock
</alltt>
</codefragment>
<subsection>Break, Redo, and Next</subsection>
<p/>
The loop control constructs <kw>break</kw>, <kw>redo</kw>, and <kw>next</kw>
let you alter the normal flow through a loop or iterator.
<p/>
<kw>break</kw> terminates the immediately enclosing loop; control resumes
at the statement following the block.  <kw>redo</kw> repeats the loop from
the start, but without reevaluating the condition or fetching the
next element (in an iterator).  <kw>next</kw> skips to the end of the
loop, effectively starting the next iteration.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  while gets
    next if /^\s*#/   # skip comments
    break if /^END/   # stop at end
                      # substitute stuff in backticks and try again
    redo if gsub!(/`(.*?)`/) { eval($1) }
    # process line ...
  end
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>/^\s*#/<nbsp/><nbsp/><nbsp/>#<nbsp/>skip<nbsp/>comments
<nbsp/><nbsp/>break<nbsp/>if<nbsp/>/^END/<nbsp/><nbsp/><nbsp/>#<nbsp/>stop<nbsp/>at<nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>substitute<nbsp/>stuff<nbsp/>in<nbsp/>backticks<nbsp/>and<nbsp/>try<nbsp/>again
<nbsp/><nbsp/>redo<nbsp/>if<nbsp/>gsub!(/`(.*?)`/)<nbsp/>{<nbsp/>eval($1)<nbsp/>}
<nbsp/><nbsp/>#<nbsp/>process<nbsp/>line<nbsp/>...
end
</alltt>
</codefragment>
<p/>
These keywords can also be used with any of the iterator-based
looping mechanisms:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  i=0
  loop do
    i += 1
    next if i < 3
    print i
    break if i > 4
  end
!-    puts
]]></fullcode>
i=0
loop<nbsp/>do
<nbsp/><nbsp/>i<nbsp/>+=<nbsp/>1
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>i<nbsp/>&lt;<nbsp/>3
<nbsp/><nbsp/>print<nbsp/>i
<nbsp/><nbsp/>break<nbsp/>if<nbsp/>i<nbsp/>&gt;<nbsp/>4
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
345
</alltt>
</codefragment>
<subsection>Retry</subsection>
<p/>
The <kw>redo</kw> statement causes a loop to repeat the current
iteration. Sometimes, though, you need to wind the loop right back to
the very beginning. The <kw>retry</kw> statement is just the
ticket. <kw>retry</kw> restarts any kind of iterator loop.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  for i in 1..100
    print "Now at #{i}. Restart? "
    retry if gets =~ /^y/i
  end
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>1..100
<nbsp/><nbsp/>print<nbsp/>"Now<nbsp/>at<nbsp/>#{i}.<nbsp/>Restart?<nbsp/>"
<nbsp/><nbsp/>retry<nbsp/>if<nbsp/>gets<nbsp/>=~<nbsp/>/^y/i
end
</alltt>
</codefragment>
<p/>
Running this interactively, you might see
<p/>
<codefragment>
<alltt><fullcode><![CDATA[Now at 1. Restart? n
Now at 2. Restart? y
Now at 1. Restart? n
 . . .
]]></fullcode>
Now<nbsp/>at<nbsp/>1.<nbsp/>Restart?<nbsp/>n
Now<nbsp/>at<nbsp/>2.<nbsp/>Restart?<nbsp/>y
Now<nbsp/>at<nbsp/>1.<nbsp/>Restart?<nbsp/>n
<nbsp/>.<nbsp/>.<nbsp/>.
</alltt>
</codefragment>
<p/>
<tt>retry</tt> will reevaluate any arguments to the iterator before
restarting it. The online Ruby documentation has the following example
of a do-it-yourself <em>until</em> loop.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def doUntil(cond)
    yield
    retry unless cond
  end

  i = 0
  doUntil(i > 3) {
    print i, " "
    i += 1
  }
!-  puts
]]></fullcode>
def<nbsp/>doUntil(cond)
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>retry<nbsp/>unless<nbsp/>cond
end
<p/>
i<nbsp/>=<nbsp/>0
doUntil(i<nbsp/>&gt;<nbsp/>3)<nbsp/>{
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
<nbsp/><nbsp/>i<nbsp/>+=<nbsp/>1
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>4
</alltt>
</codefragment>
<section>Variable Scope and Loops</section>
<p/>
The <kw>while</kw>, <kw>until</kw>, and <kw>for</kw> loops are built into the
language and do not introduce new scope; previously existing locals
can be used in the loop, and any new locals created will be available
afterward.
<p/>
The blocks used by iterators (such as <kw>loop</kw> and <kw>each</kw>) are
a little different.  Normally, the local variables created in these
blocks are not accessible outside the block.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  [ 1, 2, 3 ].each do |x|
    y = x + 1
  end
  [ x, y ]
]]></fullcode>
[<nbsp/>1,<nbsp/>2,<nbsp/>3<nbsp/>].each<nbsp/>do<nbsp/>|x|
<nbsp/><nbsp/>y<nbsp/>=<nbsp/>x<nbsp/>+<nbsp/>1
end
[<nbsp/>x,<nbsp/>y<nbsp/>]
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
prog.rb:4: undefined local variable or method `x'<br/>for #&lt;Object:0x401c2ce0&gt; (NameError)
</alltt>
</codefragment>
<p/>
However, if at the time the block executes a local variable
already exists with the same name as that of a
variable in the block, the existing local variable will be used in the 
block. Its value will therefore be available after the block finishes.
As the following example shows, this applies both to normal variables in the
block and to the block's parameters.
<p/>
<codefragment>
<fullcode><![CDATA[  x = nil
  y = nil
  [ 1, 2, 3 ].each do |x|
    y = x + 1
  end
  [ x, y ]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>x<nbsp/>=<nbsp/>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt>y<nbsp/>=<nbsp/>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3<nbsp/>].each<nbsp/>do<nbsp/>|x|</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>y<nbsp/>=<nbsp/>x<nbsp/>+<nbsp/>1</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>x,<nbsp/>y<nbsp/>]</tt></td>
  <td>&#187;</td>
  <td><tt>[3,<nbsp/>4]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
</chapter>
</ppdoc>
