<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="The Ruby Language">
<p/>
This chapter is a bottom-up look at the Ruby language. Unlike the
previous tutorial, here we're concentrating on presenting facts,
rather than motivating some of the language design features. We also
ignore the built-in classes and modules where possible. These are
covered in depth starting on page 275.
<p/>
If the content of this chapter looks familiar, it's because it should;
we've covered just about all of this in the earlier tutorial chapters.
Consider this chapter to be a self-contained reference to the core Ruby 
language.
<section>Source Layout</section>
<p/>
Ruby programs are written in 7-bit
ASCII.<footnote>Ruby also has extensive support for Kanji,    
   using the
  EUC, SJIS, or UTF-8 coding system. If a
  code set
  other than 7-bit ASCII is used, the <tt>KCODE</tt> option must be
  set appropriately, as shown on page 137.</footnote>
<p/>
Ruby is a line-oriented language. Ruby expressions and statements are
terminated at the end of a line unless the statement is obviously
incomplete---for example if the last token on a line is an operator or
comma.
A semicolon can be used to separate
multiple expressions on a line.  You can also put a backslash at the
end of a line to continue it onto the next.  Comments start
with `#' and run to the end of the
physical line. Comments are ignored during compilation.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[a = 1

b = 2; c = 3

d = 4 + 5 +      # no '\' needed
    6 + 7
    
e = 8 + 9   \
    + 10         # '\' needed
]]></fullcode>
a<nbsp/>=<nbsp/>1
<p/>
b<nbsp/>=<nbsp/>2;<nbsp/>c<nbsp/>=<nbsp/>3
<p/>
d<nbsp/>=<nbsp/>4<nbsp/>+<nbsp/>5<nbsp/>+<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>no<nbsp/>'\'<nbsp/>needed
<nbsp/><nbsp/><nbsp/><nbsp/>6<nbsp/>+<nbsp/>7
<p/>
e<nbsp/>=<nbsp/>8<nbsp/>+<nbsp/>9<nbsp/><nbsp/><nbsp/>\
<nbsp/><nbsp/><nbsp/><nbsp/>+<nbsp/>10<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>'\'<nbsp/>needed
</alltt>
</codefragment>
<p/>
Physical lines between a line starting with =begin and{=begin...=end@<tt></tt>{=begin documentation}
a line starting with =end are
ignored by the compiler and may be used for embedded documentation
(see Appendix A, which begins on page 511).
<p/>
Ruby reads its program input in a single pass, so you can pipe
programs to the compiler's <tt>stdin</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  echo 'print "Hello\n"' | ruby
]]></fullcode>
echo<nbsp/>'print<nbsp/>"Hello\n"'<nbsp/>|<nbsp/>ruby
</alltt>
</codefragment>
<p/>
If the compiler comes across a line anywhere in the source containing
just ``<tt>__END__</tt>'',
with no leading or trailing whitespace, it
treats that line as the end of the program---any subsequent lines will not be
compiled. However, these lines can be read into the running program
using the global <classname>IO</classname> object <const>DATA</const>, described
on page 217.
<subsection>BEGIN and END Blocks</subsection>
<p/>
Every Ruby source file can declare blocks of code to be run as the
file is being loaded (the <kw>BEGIN</kw> blocks) and after the program
has finished executing (the <kw>END</kw> blocks).
<p/>
<syntax>
BEGIN {
  <nt>begin code</nt>
}
<p/>
END {
  <nt>end code</nt>
}
</syntax>
<p/>
A program may include multiple <kw>BEGIN</kw> and <kw>END</kw> blocks.
<kw>BEGIN</kw> blocks are executed in the order they are encountered.
<kw>END</kw> blocks are executed in reverse order.
<subsection>General Delimited Input</subsection>
<p/>
There are alternative forms of literal strings, arrays, regular
expressions, and shell commands that are specified using a generalized
delimited syntax.
All these literals start with a percent character,
followed by a single character that identifies the literal's type.
These
characters are summarized in Table 18.1 on page 200; the actual
literals are described in the corresponding sections later in this
chapter.
<p/>
<figure type="table">
  <caption>General delimited input</caption>
  <center>
    <table>
<th>
  <td><b>Type</b></td>
  <td><b>Meaning</b></td>
  <td><b>See Page</b></td>
</th>
<tr>
  <td><tt>%q</tt></td>
  <td>Single-quoted string</td>
  <td>202</td>
</tr>
<tr>
  <td><tt>%Q</tt>, <tt>%</tt></td>
  <td>Double-quoted string</td>
  <td>202</td>
</tr>
<tr>
  <td><tt>%w</tt></td>
  <td>Array of tokens</td>
  <td>204</td>
</tr>
<tr>
  <td><tt>%r</tt></td>
  <td>Regular expression pattern</td>
  <td>205</td>
</tr>
<tr>
  <td><tt>%x</tt></td>
  <td>Shell command</td>
  <td>218</td>
</tr>
<bottomrule/></table>
<p/>
  </center>
</figure>
<p/>
Following the type character is a delimiter, which can be any
character. If the delimiter is one of the characters ``<tt>(</tt>'',
``<tt>[</tt>'', ``<tt>{</tt>'', or ``<tt>&lt;</tt>'', the literal consists of the
characters up to the matching closing delimiter, taking account of
nested delimiter pairs. For all other delimiters, the literal
comprises the characters up to the next occurrence of the delimiter
character.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  %q/this is a string/
  %q-string-
  %q(a (nested) string)
]]></fullcode>
%q/this<nbsp/>is<nbsp/>a<nbsp/>string/
%q-string-
%q(a<nbsp/>(nested)<nbsp/>string)
</alltt>
</codefragment>
<p/>
Delimited strings may continue over multiple lines.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  %q{def fred(a)
       a.each { |i| puts i }
     end}
]]></fullcode>
%q{def<nbsp/>fred(a)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>a.each<nbsp/>{<nbsp/>|i|<nbsp/>puts<nbsp/>i<nbsp/>}
<nbsp/><nbsp/><nbsp/>end}
</alltt>
</codefragment>
<p/>
<section>The Basic Types</section>
<p/>
The basic types in Ruby are numbers, strings, arrays, hashes, ranges,
symbols, and regular expressions.
<p/>
<subsection>Integer and Floating Point Numbers</subsection>
<p/>
Ruby integers are objects of class <classname>Fixnum</classname>
or <classname>Bignum</classname>.
<tt>Fixnum</tt> objects
hold integers that fit within the native machine word minus 1 bit.
Whenever a <classname>Fixnum</classname> exceeds this range, it is automatically converted
to a <tt>Bignum</tt> object, whose range is effectively limited only
by available memory.  If an operation with a <tt>Bignum</tt> result
has a final value that will fit in a <tt>Fixnum</tt>, the result will
be returned as a <tt>Fixnum</tt>.
<p/>
Integers are written using an optional leading sign, an optional base
indicator (<tt>0</tt> for octal, <tt>0x</tt> for hex, or <tt>0b</tt>
for binary), followed by a string of digits in the appropriate base.
Underscore characters are ignored in the digit string.
<p/>
You can get the integer value corresponding to an ASCII
character by preceding that character with a question mark.  Control
and meta combinations of characters can also be generated using
?\C-<em>x</em>, ?\M-<em>x</em>, and ?\M-\C-<em>x</em>.
The control version of <tt>ch</tt> is <tt>ch&amp;0x9f</tt>, and the meta
version is <tt>ch<nbsp/>|<nbsp/>0x80</tt>. You can get the integer value of a backslash
character using the sequence <tt>?\\</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[123456                    # Fixnum
123_456                   # Fixnum (underscore ignored)
-543                      # Negative Fixnum
123_456_789_123_345_789   # Bignum
0xaabb                    # Hexadecimal
0377                      # Octal
-0b1010                   # Binary (negated)
0b001_001                 # Binary
?a                        # character code
?A                        # upper case
?\C-a                     # control a = A - 0x40
?\C-A                     # case ignored for control chars
?\M-a                     # meta sets bit 7
?\M-\C-a                  # meta and control a
]]></fullcode>
123456<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Fixnum
123_456<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Fixnum<nbsp/>(underscore<nbsp/>ignored)
-543<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Negative<nbsp/>Fixnum
123_456_789_123_345_789<nbsp/><nbsp/><nbsp/>#<nbsp/>Bignum
0xaabb<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Hexadecimal
0377<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Octal
-0b1010<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Binary<nbsp/>(negated)
0b001_001<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Binary
?a<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>character<nbsp/>code
?A<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>upper<nbsp/>case
?\C-a<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>control<nbsp/>a<nbsp/>=<nbsp/>A<nbsp/>-<nbsp/>0x40
?\C-A<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>case<nbsp/>ignored<nbsp/>for<nbsp/>control<nbsp/>chars
?\M-a<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>meta<nbsp/>sets<nbsp/>bit<nbsp/>7
?\M-\C-a<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>meta<nbsp/>and<nbsp/>control<nbsp/>a
</alltt>
</codefragment>
<p/>
A numeric literal with a decimal point and/or an exponent is turned
into a <classname>Float</classname> object, corresponding to the native
architecture's <tt>double</tt> data type. You must
follow the decimal point with a digit, as 
<tt>1.e3</tt> tries to invoke the method <meth>e3</meth> in class <classname>Fixnum</classname>.
<p/>
<codefragment>
<fullcode><![CDATA[12.34
-.1234e2
1234e-2
]]></fullcode><rubycode>
<tr>
  <td><tt>12.34</tt></td>
  <td>&#187;</td>
  <td><tt>12.34</tt></td>
</tr>
<tr>
  <td><tt>-.1234e2</tt></td>
  <td>&#187;</td>
  <td><tt>-12.34</tt></td>
</tr>
<tr>
  <td><tt>1234e-2</tt></td>
  <td>&#187;</td>
  <td><tt>12.34</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
<subsubsection>Strings</subsubsection>
<p/>
Ruby provides a number of mechanisms for creating literal strings.
Each generates objects of type <classname>String</classname>.  The different
mechanisms vary in terms of how a string is delimited and how much
substitution is done on the literal's content.
<p/>
Single-quoted string literals (<tt>'</tt><em>stuff</em><tt>'</tt> and
%q/<em>stuff</em>/)
undergo the least substitution.
Both convert
the sequence <br/> into a single backslash, and the form with
single quotes converts \' into a single quote.
<p/>
<codefragment>
<fullcode><![CDATA[!-   class String
!-     def inspect
!-       to_s
!-     end
!-    end
  'hello'
  'a backslash \'\\\''
  %q/simple string/
  %q(nesting (really) works)
  %q no_blanks_here ;
]]></fullcode><rubycode>
<tr>
  <td><tt>'hello'</tt></td>
  <td>&#187;</td>
  <td><tt>hello</tt></td>
</tr>
<tr>
  <td><tt>'a<nbsp/>backslash<nbsp/>\'\\\''</tt></td>
  <td>&#187;</td>
  <td><tt>a<nbsp/>backslash<nbsp/>'\'</tt></td>
</tr>
<tr>
  <td><tt>%q/simple<nbsp/>string/</tt></td>
  <td>&#187;</td>
  <td><tt>simple<nbsp/>string</tt></td>
</tr>
<tr>
  <td><tt>%q(nesting<nbsp/>(really)<nbsp/>works)</tt></td>
  <td>&#187;</td>
  <td><tt>nesting<nbsp/>(really)<nbsp/>works</tt></td>
</tr>
<tr>
  <td><tt>%q<nbsp/>no_blanks_here<nbsp/>;</tt></td>
  <td>&#187;</td>
  <td><tt>no_blanks_here</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Double-quoted strings
("<em>stuff</em>",
%Q/<em>stuff</em>/, and
%/<em>stuff</em>/)
undergo additional substitutions, shown in Table
18.2 on page 203.
<p/>
<figure type="table">
  <caption>Substitutions in double-quoted
    strings</caption>            
  <center>
  <table>
<p/>
    <toprule/><tr>
  <td>\a</td>
  <td>Bell/alert (0x07)</td>
  <td>\<em>nnn</em></td>
  <td>Octal <em>nnn</em></td>
</tr>
<tr>
  <td>\b</td>
  <td>Backspace  (0x08)</td>
  <td>\x<em>nn</em></td>
  <td>Hex <em>nn</em></td>
</tr>
<tr>
  <td>\e</td>
  <td>Escape     (0x1b)</td>
  <td>\c<em>x</em></td>
  <td>Control-<em>x</em></td>
</tr>
<tr>
  <td>\f</td>
  <td>Formfeed   (0x0c)</td>
  <td>\C-<em>x</em></td>
  <td>Control-<em>x</em></td>
</tr>
<tr>
  <td>\n</td>
  <td>Newline    (0x0a)</td>
  <td>\M-<em>x</em></td>
  <td>Meta-<em>x</em></td>
</tr>
<tr>
  <td>\r</td>
  <td>Return     (0x0d)</td>
  <td>\M-\C-<em>x</em></td>
  <td>Meta-control-<em>x</em></td>
</tr>
<tr>
  <td>\s</td>
  <td>Space      (0x20)</td>
  <td>\<em>x</em></td>
  <td><em>x</em></td>
</tr>
<tr>
  <td>\t</td>
  <td>Tab        (0x09)</td>
  <td>#{expr}</td>
  <td>Value of <em>expr</em></td>
</tr>
<tr>
  <td>\v</td>
  <td>Vertical tab (0x0b)</td>
</tr>
<bottomrule/></table>
<p/>
</center>
</figure>
<p/>
<codefragment>
<fullcode><![CDATA[!-   class String
!-     def inspect
!-       to_s
!-     end
!-    end
a  = 123
"\123mile"
"Say \"Hello\""
%Q!"I said 'nuts'," I said!
%Q{Try #{a + 1}, not #{a - 1}}
%<Try #{a + 1}, not #{a - 1}>
"Try #{a + 1}, not #{a - 1}"
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/><nbsp/>=<nbsp/>123</tt></td>
</tr>
<tr>
  <td><tt>"\123mile"</tt></td>
  <td>&#187;</td>
  <td><tt>Smile</tt></td>
</tr>
<tr>
  <td><tt>"Say<nbsp/>\"Hello\""</tt></td>
  <td>&#187;</td>
  <td><tt>Say<nbsp/>"Hello"</tt></td>
</tr>
<tr>
  <td><tt>%Q!"I<nbsp/>said<nbsp/>'nuts',"<nbsp/>I<nbsp/>said!</tt></td>
  <td>&#187;</td>
  <td><tt>"I<nbsp/>said<nbsp/>'nuts',"<nbsp/>I<nbsp/>said</tt></td>
</tr>
<tr>
  <td><tt>%Q{Try<nbsp/>#{a<nbsp/>+<nbsp/>1},<nbsp/>not<nbsp/>#{a<nbsp/>-<nbsp/>1}}</tt></td>
  <td>&#187;</td>
  <td><tt>Try<nbsp/>124,<nbsp/>not<nbsp/>122</tt></td>
</tr>
<tr>
  <td><tt>%&lt;Try<nbsp/>#{a<nbsp/>+<nbsp/>1},<nbsp/>not<nbsp/>#{a<nbsp/>-<nbsp/>1}&gt;</tt></td>
  <td>&#187;</td>
  <td><tt>Try<nbsp/>124,<nbsp/>not<nbsp/>122</tt></td>
</tr>
<tr>
  <td><tt>"Try<nbsp/>#{a<nbsp/>+<nbsp/>1},<nbsp/>not<nbsp/>#{a<nbsp/>-<nbsp/>1}"</tt></td>
  <td>&#187;</td>
  <td><tt>Try<nbsp/>124,<nbsp/>not<nbsp/>122</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Strings can continue across multiple input lines, in which case they
will contain newline characters. It is also possible to use <em>here
  documents</em> to express long string literals. Whenever Ruby parses the sequence
&lt;&lt;<em>identifier</em> or &lt;&lt;<em>quoted string</em>, it
replaces it with a string literal built from successive logical input
lines.
It stops building the string when it finds a line that starts
with the identifier or the <em>quoted string</em>.  You can put a minus
sign immediately after the &lt;&lt; characters, in which case the
terminator can be indented from the left margin.  If a quoted
string was used to specify the terminator, its quoting rules will be
applied to the here document; otherwise, double-quoting rules apply.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[a = 123
print <<HERE
Double quoted \
here document.
Sum = #{a + 1}
HERE

print <<-'THERE'
    This is single quoted.
    The above used #{a + 1}
    THERE
]]></fullcode>
a<nbsp/>=<nbsp/>123
print<nbsp/>&lt;&lt;HERE
Double<nbsp/>quoted<nbsp/>\
here<nbsp/>document.
Sum<nbsp/>=<nbsp/>#{a<nbsp/>+<nbsp/>1}
HERE
<p/>
print<nbsp/>&lt;&lt;-'THERE'
<nbsp/><nbsp/><nbsp/><nbsp/>This<nbsp/>is<nbsp/>single<nbsp/>quoted.
<nbsp/><nbsp/><nbsp/><nbsp/>The<nbsp/>above<nbsp/>used<nbsp/>#{a<nbsp/>+<nbsp/>1}
<nbsp/><nbsp/><nbsp/><nbsp/>THERE
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Double<nbsp/>quoted<nbsp/>here<nbsp/>document.
Sum<nbsp/>=<nbsp/>124
<nbsp/><nbsp/><nbsp/><nbsp/>This<nbsp/>is<nbsp/>single<nbsp/>quoted.
<nbsp/><nbsp/><nbsp/><nbsp/>The<nbsp/>above<nbsp/>used<nbsp/>#{a<nbsp/>+<nbsp/>1}
</alltt>
</codefragment>
<p/>
Adjacent single- and double-quoted strings in the input are
concatenated to form a single <tt>String</tt> object.
<p/>
<codefragment>
<fullcode><![CDATA['Con' "cat" 'en' "ate"
]]></fullcode><rubycode>
<tr>
  <td><tt>'Con'<nbsp/>"cat"<nbsp/>'en'<nbsp/>"ate"</tt></td>
  <td>&#187;</td>
  <td><tt>"Concatenate"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Strings are stored as sequences of 8-bit bytes,<footnote>For use
  in Japan, the <tt>jcode</tt> library supports a set of operations of
  strings written with EUC, SJIS, or UTF-8
  encoding.  
  The underlying string, however, is still accessed as a
  series of bytes.</footnote> and each byte may contain any of the 256 8-bit
values, including null and newline.
The substitution mechanisms in
Table 18.2 on page 203 allow nonprinting characters to be
inserted conveniently and portably.
<p/>
Every time a string literal is used in an assignment or as a
parameter, a new <classname>String</classname> object is created. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  for i in 1..3
    print 'hello'.id, " "
  end
!-    puts
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>1..3
<nbsp/><nbsp/>print<nbsp/>'hello'.id,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
537763324<nbsp/>537763034<nbsp/>537763004
</alltt>
</codefragment>
<p/>
The documentation for class <classname>String</classname> starts on page 363.
<subsection>Ranges</subsection>
<p/>
Outside the context of a conditional expression, 
<em>expr</em><tt>..</tt><em>expr</em> and <em>expr</em><tt>...</tt><em>expr</em>
construct <classname>Range</classname> objects.
The two-dot form is an inclusive range;
the one with three dots is a range that excludes its last element.
See the description of class <classname>Range</classname> on page 359 for
details. Also see the description of conditional expressions
on page 222 for other uses of ranges.
<subsection>Arrays</subsection>
<p/>
Literals of class <classname>Array</classname> are created by placing a comma-separated
series of object references between square brackets. A trailing comma
is ignored.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- fred = 1
!- def barney(a)
!- end
  arr = [ fred, 10, 3.14, "This is a string", barney("pebbles"), ]
]]></fullcode>
arr<nbsp/>=<nbsp/>[<nbsp/>fred,<nbsp/>10,<nbsp/>3.14,<nbsp/>"This<nbsp/>is<nbsp/>a<nbsp/>string",<nbsp/>barney("pebbles"),<nbsp/>]
</alltt>
</codefragment>
<p/>
Arrays of strings can be constructed using a shortcut notation,
<tt>%w</tt>,
which extracts space-separated tokens into successive
elements of the array. A space can be escaped with a backslash.
This is a form of general delimited input,
described on pages 200--201.
<p/>
<codefragment>
<fullcode><![CDATA[  arr = %w( fred wilma barney betty great\ gazoo )
  arr
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>arr<nbsp/>=<nbsp/>%w(<nbsp/>fred<nbsp/>wilma<nbsp/>barney<nbsp/>betty<nbsp/>great\<nbsp/>gazoo<nbsp/>)</tt></td>
</tr>
<tr>
  <td><tt>arr</tt></td>
  <td>&#187;</td>
  <td><tt>["fred",<nbsp/>"wilma",<nbsp/>"barney",<nbsp/>"betty",<nbsp/>"great<nbsp/>gazoo"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Hashes</subsection>
<p/>
A literal Ruby <classname>Hash</classname> is created by placing a list of key/value
pairs between braces, with either a comma or the sequence <tt>=&gt;</tt>
between the key and the value. A trailing comma is ignored.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  colors = { "red"   => 0xf00, 
             "green" => 0x0f0,
             "blue"  => 0x00f
           }
]]></fullcode>
colors<nbsp/>=<nbsp/>{<nbsp/>"red"<nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>0xf00,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"green"<nbsp/>=&gt;<nbsp/>0x0f0,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"blue"<nbsp/><nbsp/>=&gt;<nbsp/>0x00f
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>}
</alltt>
</codefragment>
<p/>
There is no requirement for the keys and/or values in a particular
hash to have the same type.
<subsubsection>Requirements for a Hash Key</subsubsection>
<p/>
The only restriction for a hash key is that it must respond to the
message <meth>hash</meth> with a hash value, and the hash value for a
given key must not change.
This means that certain classes (such as
<classname>Array</classname> and <classname>Hash</classname>, as of this writing) can't conveniently be used
as keys, because their hash values can change based on their contents.
<p/>
If you keep an external reference to an object that is used as a key,
and use that reference to alter the object and change its hash value,
the hash lookup based on that key may not work.
<p/>
Because strings are the most frequently used keys, and because string
contents are often changed, Ruby treats string keys specially. If you
use a <classname>String</classname> object as a hash key, the hash will duplicate the
string internally and will use that copy as its key. Any changes
subsequently made to the original string will not affect the hash.
<p/>
If you write your own classes and use instances of them as hash keys, you
need to make sure that either (a) the hashes of the key objects
don't change once the objects have been created or (b) you remember
to call the <cim><file>hash</file><front>Hash</front><back>rehash</back><mref>rehash</mref></cim> method to reindex the hash whenever a
key hash <em>is</em> changed.
<subsection>Symbols</subsection>
<p/>
A Ruby symbol is the internal representation of a name. You construct
the symbol for a name by preceding the name with a colon. A particular 
name will always generate the same symbol, regardless of how that name 
is used within the program.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  :Object
  :myVariable
]]></fullcode>
:Object
:myVariable
</alltt>
</codefragment>
<p/>
Other languages call this process ``interning,'' and call symbols
``atoms.''
<subsection>Regular Expressions</subsection>
<p/>
Regular expression literals are objects of type <classname>Regexp</classname>. They can
be created by explicitly calling the <ccm><file>regexp</file><front>Regexp</front><back>new</back><mref>new</mref></ccm> constructor, or
by using the literal forms, /<em>pattern</em>/ and
<tt>%r{</tt><em>pattern</em><tt>}</tt>. The <tt>%r</tt> construct is
a form of general delimited input (described
on pages 200--201).
<p/>
<syntax>
/pattern/
/pattern/<nt>options</nt>
%r{pattern}
%r{pattern}<nt>options</nt>
Regexp.new( 'pattern' <opt>, <nt>options</nt></opt> )
</syntax>
<subsubsection>Regular Expression Options</subsubsection>
<p/>
A regular expression may include one or more options that modify the
way the pattern matches strings. If you're using literals to create
the <classname>Regexp</classname> object, then the options comprise one or more characters placed
immediately after the terminator. If you're using <tt>Regexp.new</tt>, the 
options are constants used as the second parameter of the constructor.
<p/>
<table>
<tr>
  <td><tt>i</tt></td>
  <td><em>Case Insensitive</em>. The pattern match will ignore    
  the case of letters in the pattern and string. Matches are also
  case-insensitive if the global variable <var>$=</var> is set.</td>
</tr>
<tr>
  <td><tt>o</tt></td>
  <td><em>Substitute Once</em>. Any <tt>#{...}</tt> substitutions
  in    
  a particular regular expression literal will be performed just once,
  the first time it is evaluated. Otherwise, the substitutions
  will be performed every time the literal generates a <classname>Regexp</classname> object.</td>
</tr>
<tr>
  <td><tt>m</tt></td>
  <td><em>Multiline Mode</em>. Normally, ``.'' matches any    
  character except a newline. With the <tt>/m</tt> option, ``.'' matches
  any character.</td>
</tr>
<tr>
  <td><tt>x</tt></td>
  <td><em>Extended Mode</em>.
  Complex regular expressions can be difficult to read. The `x'
  option    
  allows you to insert spaces, newlines, and comments in the pattern to
  make it more readable.</td>
</tr>
</table>
<p/>
<subsubsection>Regular Expression Patterns</subsubsection>
<p/>
<dl>
<dt><b><em>regular characters</em></b></dt><dd>    All characters except ., |, (, ), [, \, ^, {, +, $, *, and ? match
    themselves. To match one of these characters, precede it with a
    backslash.
<p/>
</dd><dt><b><tt>^</tt></b></dt><dd>  Matches the beginning of a line.
<p/>
</dd><dt><b><tt>$</tt></b></dt><dd>  Matches the end of a line.
<p/>
</dd><dt><b><tt>\A</tt></b></dt><dd>  Matches the beginning of the string.
<p/>
</dd><dt><b><tt>\z</tt></b></dt><dd>  Matches the end of the string.
<p/>
</dd><dt><b><tt>\Z</tt></b></dt><dd>  Matches the end of the string <em>unless</em> the string
  ends with a ``\n'', in
  which case it matches just before the ``\n''.
<p/>
</dd><dt><b><tt>\b</tt>, <tt>\B</tt></b></dt><dd>    Match word boundaries and nonword boundaries respectively.
<p/>
</dd><dt><b><tt>[</tt><em>characters</em><tt>]</tt></b></dt><dd>  A character class  matches any single character between the
  brackets.  The characters <tt>|, (, ), [, ^, $, *,</tt> and <tt>?</tt>,
  which have special meanings elsewhere in patterns, lose their
  special significance between brackets.  The sequences
  <tt>\</tt><em>nnn</em>, <tt>\x</tt><em>nn</em>, <tt>\c</tt><em>x</em>, <tt>\C-</tt><em>x</em>, <tt>\M-</tt><em>x</em>, and <tt>\M-\C-</tt><em>x</em>
  have the meanings shown in Table 18.2 on page 203.  The
  sequences <tt>\d</tt>, <tt>\D</tt>, <tt>\s</tt>, <tt>\S</tt>, <tt>\w</tt>, and <tt>\W</tt> are abbreviations for groups of characters, as
  shown in Table 5.1 on page 59.  The sequence c<sub>1</sub>-c<sub>2</sub>
  represents all the characters between c<sub>1</sub> and c<sub>2</sub>, inclusive.
  Literal <tt>]</tt> or <tt>-</tt> characters must appear immediately after
  the opening bracket.  An uparrow (^) immediately following the
  opening bracket negates the sense of the match---the pattern matches
  any character that isn't in the character class.
<p/>
</dd><dt><b><tt>\d</tt>, <tt>\s</tt>, <tt>\w</tt></b></dt><dd>      Are abbreviations for character classes that match digits, whitespace,
  and word characters, respectively. \D, \S, and \W match
  characters that are not digits, whitespace, or word
  characters. These abbreviations are summarized in Table
  5.1 on page 59.
<p/>
</dd><dt><b><tt>.</tt> (period)</b></dt><dd>  Appearing outside brackets, matches any character except a newline.
  (With the <tt>/m</tt> option, it matches newline, too).
<p/>
</dd><dt><b><em>re</em><tt>*</tt></b></dt><dd>  Matches zero or more occurrences of <em>re</em>.
<p/>
</dd><dt><b><em>re</em><tt>+</tt></b></dt><dd>  Matches one or more occurrences of <em>re</em>.
<p/>
</dd><dt><b><em>re</em><tt>{m,n}</tt></b></dt><dd>  Matches at least ``m'' and at most ``n'' occurrences of <em>re</em>.
<p/>
</dd><dt><b><em>re</em><tt>?</tt></b></dt><dd>  Matches zero or one occurrence of <em>re</em>.
  The <tt>*</tt>, <tt>+</tt>, and <tt>{m,n}</tt> modifiers are greedy by
  default. Append a question mark to make them minimal.
<p/>
</dd><dt><b><em>re1</em><tt>|</tt><em>re2</em></b></dt><dd>  Matches either <em>re1</em> or <em>re2</em>.  <tt>|</tt> has a low
  precedence.
<p/>
</dd><dt><b><tt>(...)</tt></b></dt><dd>  Parentheses are used to group regular expressions. For example, the
  pattern <tt>/abc+/</tt> matches a string containing an ``a,'' a ``b,''
  and one or more ``c''s. <tt>/(abc)+/</tt> matches one or more sequences
  of ``abc''.  Parentheses are also used to collect the results of
  pattern matching. For each opening parenthesis, Ruby stores the
  result of the partial match between it and the corresponding closing
  parenthesis as successive groups. Within the same pattern,
  <tt>\1</tt> refers to the match of the first group, <tt>\2</tt> the
  second group, and so on.  Outside the pattern, the special variables
  <tt>$1</tt>, <tt>$2</tt>, and so on, serve the same purpose.
</dd></dl>
<subsubsection>Substitutions</subsubsection>
<p/>
<dl>
<dt><b><tt>#{...}</tt></b></dt><dd>  Performs an expression substitution, as with strings. By default, the
  substitution is performed each time a regular expression literal is
  evaluated. With the <tt>/o</tt> option, it is performed just the first
  time.
<p/>
</dd><dt><b><tt>\0, \1, \2, ... \9, \&amp;, \`, \', \+</tt></b></dt><dd>    Substitutes the value matched by the <em>n</em>th grouped
  subexpression, or by the entire match, pre- or postmatch, or the
  highest group.
</dd></dl>
<subsubsection>Extensions</subsubsection>
<p/>
In common with Perl and Python, Ruby regular expressions offer some
extensions over traditional Unix regular expressions. All the extensions are
entered between the characters <tt>(?</tt><nbsp/>and<nbsp/><tt>)</tt>. The parentheses
that bracket these extensions are groups, but they do not generate
backreferences: they do not set the values of <tt>\1</tt> and <tt>$1</tt>
etc.
<p/>
<dl>
<dt><b><tt>(?# <em>comment</em>)</tt></b></dt><dd>  Inserts a comment into the pattern. The content is ignored during
  pattern matching.
<p/>
</dd><dt><b><tt>(?:<em>re</em>)</tt></b></dt><dd>
  Makes <em>re</em> into a group without generating backreferences. This 
  is often useful when you need to group a set of constructs but don't 
  want the group to set the value of <var>$1</var> or whatever. In the
  example that follows, both patterns match a date with either colons
  or spaces between the month, day, and year. The first form stores
  the separator character in <var>$2</var> and <var>$4</var>, while the second
  pattern doesn't store the separator in an external variable.
<p/>
<codefragment>
<fullcode><![CDATA[    date = "12/25/01"
#    date =~ %r{(\d+)(/|:)(\d+)(/|:)(\d+)}
!-    date =~ %r{(\d+)(/|:)(\d+)(/|:)(\d+)}
    [$1,$2,$3,$4,$5]
#    date =~ %r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}
!-    date =~ %r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}
    [$1,$2,$3]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>date<nbsp/>=<nbsp/>"12/25/01"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>date<nbsp/>=~<nbsp/>%r{(\d+)(/|:)(\d+)(/|:)(\d+)}</tt></td>
</tr>
<tr>
  <td><tt>[$1,$2,$3,$4,$5]</tt></td>
  <td>&#187;</td>
  <td><tt>["12",<nbsp/>"/",<nbsp/>"25",<nbsp/>"/",<nbsp/>"01"]</tt></td>
</tr>
<tr>
<td colspan="3"><tt>date<nbsp/>=~<nbsp/>%r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}</tt></td>
</tr>
<tr>
  <td><tt>[$1,$2,$3]</tt></td>
  <td>&#187;</td>
  <td><tt>["12",<nbsp/>"25",<nbsp/>"01"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
</dd><dt><b><tt>(?=<em>re</em>)</tt></b></dt><dd>
  Matches <em>re</em> at this point, but does not consume it (also known 
  charmingly as ``zero-width positive lookahead''). This lets
  you look forward for the context of a match without affecting
  <var>$&amp;</var>. In this example, the <meth>scan</meth> method matches words
  followed by a comma, but the commas are not included in the result.
<p/>
<codefragment>
<fullcode><![CDATA[    str = "red, white, and blue"
    str.scan(/[a-z]+(?=,)/)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>str<nbsp/>=<nbsp/>"red,<nbsp/>white,<nbsp/>and<nbsp/>blue"</tt></td>
</tr>
<tr>
  <td><tt>str.scan(/[a-z]+(?=,)/)</tt></td>
  <td>&#187;</td>
  <td><tt>["red",<nbsp/>"white"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
</dd><dt><b><tt>(?!<em>re</em>)</tt></b></dt><dd>
  Matches if <em>re</em> does not match at this point. Does not
  consume the match (zero-width negative lookahead). For example,
  <tt>/hot(?!dog)(\w+)/</tt> matches any word that contains the
  letters ``hot'' that aren't followed by ``dog'', returning the end
  of the word in <var>$1</var>.
<p/>
</dd><dt><b><tt>(?&gt;<em>re</em>)</tt></b></dt><dd>
  Nests an independent regular expression within the first regular
  expression.  
  This expression is anchored at the current match position. If it
  consumes characters, these will no longer be available to the
  higher-level regular expression. This construct therefore inhibits
  backtracking, which can be a performance enhancement. For example,
  the pattern <tt>/a.*b.*a/</tt> takes exponential time when matched
  against a string containing an ``a'' followed by a number of ``b''s, 
  but with no trailing ``a.'' However, this can be avoided by using a
  nested regular expression <tt>/a(?&gt;.*b).*a/</tt>. In this form, the
  nested expression consumes all the the input string up to the last
  possible ``b'' character. When the check for a trailing ``a'' then
  fails, there is no need to backtrack, and the pattern match fails promptly.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    require "benchmark"
    include Benchmark
    str = "a" + ("b" * 5000)
    bm(8) do |test|
      test.report("Normal:") { str =~ /a.*b.*a/ }
      test.report("Nested:") { str =~ /a(?>.*b).*a/ }
    end
]]></fullcode>
require<nbsp/>"benchmark"
include<nbsp/>Benchmark
str<nbsp/>=<nbsp/>"a"<nbsp/>+<nbsp/>("b"<nbsp/>*<nbsp/>5000)
bm(8)<nbsp/>do<nbsp/>|test|
<nbsp/><nbsp/>test.report("Normal:")<nbsp/>{<nbsp/>str<nbsp/>=~<nbsp/>/a.*b.*a/<nbsp/>}
<nbsp/><nbsp/>test.report("Nested:")<nbsp/>{<nbsp/>str<nbsp/>=~<nbsp/>/a(?&gt;.*b).*a/<nbsp/>}
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>user<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>system<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>total<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>real
Normal:<nbsp/><nbsp/><nbsp/>4.170000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>4.170000<nbsp/>(<nbsp/><nbsp/>4.150970)
Nested:<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/>(<nbsp/><nbsp/>0.001529)
</alltt>
</codefragment>
<p/>
</dd><dt><b><tt>(?imx)</tt></b></dt><dd>
    Turns on the corresponding ``i,'' ``m,'' or ``x'' option. If used
  inside a group, the effect is limited to that group.
<p/>
</dd><dt><b><tt>(?-imx)</tt></b></dt><dd>
  Turns off the ``i,'' ``m,'' or ``x'' option.
<p/>
</dd><dt><b><tt>(?imx:<em>re</em>)</tt></b></dt><dd>
  Turns on the ``i,'' ``m,'' or ``x'' option for <em>re</em>.
<p/>
</dd><dt><b><tt>(?-imx:<em>re</em>)</tt></b></dt><dd>
  Turns off the ``i,'' ``m,'' or ``x'' option for <em>re</em>.
<p/>
</dd></dl>
<section>Names</section>
<p/>
Ruby names are used to refer to constants, variables, methods,
classes, and modules. The first character of a name helps Ruby to
distinguish its intended use.  Certain names, listed in Table
18.3 on page 210, are reserved words and should not be used as
variable, method, class, or module names.
<p/>
<figure type="table">
  <caption>Reserved words</caption>  
    <table>
<p/>
    <toprule/><tr>
  <td>__FILE__</td>
  <td>and</td>
  <td>def</td>
  <td>end</td>
  <td>in</td>
  <td>or</td>
  <td>self</td>
  <td>unless</td>
</tr>
<tr>
  <td>__LINE__</td>
  <td>begin</td>
  <td>defined?</td>
  <td>ensure</td>
  <td>module</td>
  <td>redo</td>
  <td>super</td>
  <td>until</td>
</tr>
<tr>
  <td>BEGIN</td>
  <td>break</td>
  <td>do</td>
  <td>false</td>
  <td>next</td>
  <td>rescue</td>
  <td>then</td>
  <td>when</td>
</tr>
<tr>
  <td>END</td>
  <td>case</td>
  <td>else</td>
  <td>for</td>
  <td>nil</td>
  <td>retry</td>
  <td>true</td>
  <td>while</td>
</tr>
<tr>
  <td>alias</td>
  <td>class</td>
  <td>elsif</td>
  <td>if</td>
  <td>not</td>
  <td>return</td>
  <td>undef</td>
  <td>yield</td>
</tr>
<bottomrule/></table>
<p/>
</figure>
<p/>
In these descriptions, <em>lowercase letter</em> means the characters
``a'' though ``z'', as well as ``_'', the underscore. <em>Uppercase
  letter</em> means ``A'' though ``Z,'' and <em>digit</em> means ``0''
through ``9.'' <em>Name characters</em> means any combination of upper-
and lowercase letters and digits.
<p/>
A local variable name consists of a lowercase letter followed by name
characters.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  fred  anObject  _x  three_two_one
]]></fullcode>
fred<nbsp/><nbsp/>anObject<nbsp/><nbsp/>_x<nbsp/><nbsp/>three_two_one
</alltt>
</codefragment>
<p/>
An instance variable name starts with an ``at'' sign (``<tt>@</tt>'') followed by an
upper- or lowercase letter, optionally followed by name 
characters.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  @name  @_  @Size
]]></fullcode>
@name<nbsp/><nbsp/>@_<nbsp/><nbsp/>@Size
</alltt>
</codefragment>
<p/>
A class variable name starts with two ``at'' signs (``<tt>@@</tt>'')
followed by an upper- or lowercase letter, optionally followed by name 
characters.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  @@name  @@_  @@Size
]]></fullcode>
@@name<nbsp/><nbsp/>@@_<nbsp/><nbsp/>@@Size
</alltt>
</codefragment>
<p/>
A constant name starts with an uppercase letter followed by name characters.
Class names and module names are constants, and follow the constant
naming conventions.  By convention, constant variables are normally
spelled using uppercase letters and underscores throughout.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Math
    PI = 3.1415926
  end
  class BigBlob
]]></fullcode>
module<nbsp/>Math
<nbsp/><nbsp/>PI<nbsp/>=<nbsp/>3.1415926
end
class<nbsp/>BigBlob
</alltt>
</codefragment>
<p/>
Global variables, and some special system variables, start with a
dollar sign (``<tt>$</tt>'') followed by name characters. In addition,
there is a set of two-character variable names in which the second
character is a punctuation character. These predefined variables are
listed starting on page 213. Finally, a global variable name
can be formed using ``<tt>$-</tt>'' followed by <em>any</em> single character.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  $params  $PROGRAM  $!  $_  $-a  $-.
]]></fullcode>
$params<nbsp/><nbsp/>$PROGRAM<nbsp/><nbsp/>$!<nbsp/><nbsp/>$_<nbsp/><nbsp/>$-a<nbsp/><nbsp/>$-.
</alltt>
</codefragment>
<p/>
Method names are described in the section beginning on page 225.
<subsection>Variable/Method Ambiguity</subsection>
<p/>
When Ruby sees a name such as ``a'' in an expression, it needs to
determine if it is a local variable reference or a call to a method
with no parameters.
To decide which is the case, Ruby uses a
heuristic.  As Ruby reads a source file, it keeps track of symbols
that have been assigned to. It assumes that these symbols are variables. When it
subsequently comes across a symbol that might be either a variable or
a method call, it checks to see if it has seen a prior assignment to
that symbol. If so, it treats the symbol as a variable; otherwise it
treats it as a method call.  As a somewhat pathological case of this,
consider the following code fragment, submitted by Clemens Hintze.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def a
    print "Function 'a' called\n"
    99
  end
 
  for i in 1..2
    if i == 2
      print "a=", a, "\n"
    else
      a = 1
      print "a=", a, "\n"
    end
  end 
]]></fullcode>
def<nbsp/>a
<nbsp/><nbsp/>print<nbsp/>"Function<nbsp/>'a'<nbsp/>called\n"
<nbsp/><nbsp/>99
end
<p/>
for<nbsp/>i<nbsp/>in<nbsp/>1..2
<nbsp/><nbsp/>if<nbsp/>i<nbsp/>==<nbsp/>2
<nbsp/><nbsp/><nbsp/><nbsp/>print<nbsp/>"a=",<nbsp/>a,<nbsp/>"\n"
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>a<nbsp/>=<nbsp/>1
<nbsp/><nbsp/><nbsp/><nbsp/>print<nbsp/>"a=",<nbsp/>a,<nbsp/>"\n"
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
a=1
Function<nbsp/>'a'<nbsp/>called
a=99
</alltt>
</codefragment>
<p/>
During the parse, Ruby sees the use of ``a'' in the first print
statement and, as it hasn't yet seen any assignment to ``a,'' assumes
that it is a method call. By the time it gets to the second print
statement, though, it <em>has</em> seen an assignment, and so treats
``a'' as a variable.
<p/>
Note that the assignment does not have to be executed---Ruby just has
to have seen it. This program does not raise an error.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a = 1 if false; a
]]></fullcode>
a<nbsp/>=<nbsp/>1<nbsp/>if<nbsp/>false;<nbsp/>a
</alltt>
</codefragment>
<section>Variables and Constants</section>
<p/>
Ruby variables and constants hold references to objects.
Variables
themselves do not have an intrinsic type.  Instead, the type of a
variable is defined solely by the messages to which the object
referenced by the
variable responds.<footnote>When we say that a variable
  is not typed, we mean that any given variable can at different times
  hold references to objects of many different types.</footnote>
<p/>
A Ruby <em>constant</em> is also a reference to an object.
Constants are 
created when they are first assigned to (normally in a class or module 
definition).  Ruby, unlike less flexible languages, lets you alter the value
of a constant, although this will generate a warning message.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  MY_CONST = 1
  MY_CONST = 2   # generates a warning
]]></fullcode>
MY_CONST<nbsp/>=<nbsp/>1
MY_CONST<nbsp/>=<nbsp/>2<nbsp/><nbsp/><nbsp/>#<nbsp/>generates<nbsp/>a<nbsp/>warning
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
prog.rb:2:<nbsp/>warning:<nbsp/>already<nbsp/>initialized<nbsp/>constant<nbsp/>MY_CONST
</alltt>
</codefragment>
<p/>
Note that although constants should not be changed, you can alter the
internal states of the objects they reference.
<p/>
<codefragment>
<fullcode><![CDATA[  MY_CONST = "Tim"
  MY_CONST[0] = "J"   # alter string referenced by constant
  MY_CONST
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>MY_CONST<nbsp/>=<nbsp/>"Tim"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>MY_CONST[0]<nbsp/>=<nbsp/>"J"<nbsp/><nbsp/><nbsp/>#<nbsp/>alter<nbsp/>string<nbsp/>referenced<nbsp/>by<nbsp/>constant</tt></td>
</tr>
<tr>
  <td><tt>MY_CONST</tt></td>
  <td>&#187;</td>
  <td><tt>"Jim"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Assignment potentially <em>aliases</em> objects,
giving the same object different names.
<subsection>Scope of Constants and Variables</subsection>
<p/>
Constants defined within a class or module may be accessed unadorned
anywhere within the class or module.
Outside the class or module, they
may be accessed using the scope operator, ``<tt>::</tt>'' prefixed by an
expression that returns the appropriate class or module object.
Constants defined outside any class or module may be accessed
unadorned or by using the scope operator ``<tt>::</tt>'' with no prefix. Constants may not
be defined in methods.
<p/>
<codefragment>
<fullcode><![CDATA[  OUTER_CONST = 99
  class Const
    def getConst
      CONST
    end
    CONST = OUTER_CONST + 1
  end
  Const.new.getConst
  Const::CONST
  ::OUTER_CONST
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>OUTER_CONST<nbsp/>=<nbsp/>99</tt></td>
</tr>
<tr>
<td colspan="3"><tt>class<nbsp/>Const</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>getConst</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>CONST</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>CONST<nbsp/>=<nbsp/>OUTER_CONST<nbsp/>+<nbsp/>1</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>Const.new.getConst</tt></td>
  <td>&#187;</td>
  <td><tt>100</tt></td>
</tr>
<tr>
  <td><tt>Const::CONST</tt></td>
  <td>&#187;</td>
  <td><tt>100</tt></td>
</tr>
<tr>
  <td><tt>::OUTER_CONST</tt></td>
  <td>&#187;</td>
  <td><tt>99</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Global variables are available throughout a program. Every reference
to a particular global name returns the same object.  Referencing an
uninitialized global variable returns <tt>nil</tt>.
<p/>
Class variables are available throughout a class or module body. Class
variables must be initialized before use.  A class variable is shared
among all instances of a class and is available within the class
itself.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Song
    @@count = 0
    def initialize
      @@count += 1
    end
    def Song.getCount
      @@count
    end
  end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>@@count<nbsp/>=<nbsp/>0
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>@@count<nbsp/>+=<nbsp/>1
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>Song.getCount
<nbsp/><nbsp/><nbsp/><nbsp/>@@count
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Class variables belong to the innermost enclosing class or
module. Class variables used at the top level are defined in
<classname>Object</classname>, and behave like global variables. Class variables defined
within singleton methods belong to the receiver if the receiver is a
class or a module; otherwise, they belong to the class of the receiver.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Holder
    @@var = 99
    def Holder.var=(val)
      @@var = val
    end
  end
  
  a = Holder.new
  def a.var
    @@var
  end
]]></fullcode>
class<nbsp/>Holder
<nbsp/><nbsp/>@@var<nbsp/>=<nbsp/>99
<nbsp/><nbsp/>def<nbsp/>Holder.var=(val)
<nbsp/><nbsp/><nbsp/><nbsp/>@@var<nbsp/>=<nbsp/>val
<nbsp/><nbsp/>end
end
<p/>
a<nbsp/>=<nbsp/>Holder.new
def<nbsp/>a.var
<nbsp/><nbsp/>@@var
end
</alltt>
</codefragment>
<p/>
<codefragment>
<fullcode><![CDATA[!-  class Holder
!-    @@var = 99
!-    def Holder.var=(val)
!-      @@var = val
!-    end
!-  end
!-  
!-  a = Holder.new
!-  def a.var
!-    @@var
!-  end
  Holder.var = 123
  a.var
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>Holder.var<nbsp/>=<nbsp/>123</tt></td>
</tr>
<tr>
  <td><tt>a.var</tt></td>
  <td>&#187;</td>
  <td><tt>123</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Instance variables are available within instance methods throughout a
class body. Referencing an uninitialized instance variable returns
<tt>nil</tt>. Each instance of a class has a unique set of instance
variables. Instance variables are not available to class methods.
<p/>
Local variables are unique in that their scopes are statically determined
but their existence is established dynamically.
<p/>
A local variable is created dynamically when it is first assigned a value
during program execution. However, the scope of a local variable is
statically determined to be: the immediately enclosing block, method
definition, class definition, module definition, or top-level
program. Referencing a local variable that is in scope but that has
not yet been created generates a <exception>NameError</exception> exception.
<p/>
Local variables with the same name are different variables if they
appear in disjoint scopes.
<p/>
Method parameters are considered to be variables local to that method.
<p/>
Block parameters are assigned values when the block is invoked.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a = [ 1, 2, 3 ]
  a.each { |i|  puts i  }  # i local to block
  a.each { |$i| puts $i }  # assigns to global $i
  a.each { |@i| puts @i }  # assigns to instance variable @i
  a.each { |I|  puts I  }  # generates warning assigning to constant
  a.each { |b.meth| }      # invokes meth= in object b
  sum = 0
  var = nil
  a.each { |var| sum += var }  # uses sum and var from enclosing scope
]]></fullcode>
a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>2,<nbsp/>3<nbsp/>]
a.each<nbsp/>{<nbsp/>|i|<nbsp/><nbsp/>puts<nbsp/>i<nbsp/><nbsp/>}<nbsp/><nbsp/>#<nbsp/>i<nbsp/>local<nbsp/>to<nbsp/>block
a.each<nbsp/>{<nbsp/>|$i|<nbsp/>puts<nbsp/>$i<nbsp/>}<nbsp/><nbsp/>#<nbsp/>assigns<nbsp/>to<nbsp/>global<nbsp/>$i
a.each<nbsp/>{<nbsp/>|@i|<nbsp/>puts<nbsp/>@i<nbsp/>}<nbsp/><nbsp/>#<nbsp/>assigns<nbsp/>to<nbsp/>instance<nbsp/>variable<nbsp/>@i
a.each<nbsp/>{<nbsp/>|I|<nbsp/><nbsp/>puts<nbsp/>I<nbsp/><nbsp/>}<nbsp/><nbsp/>#<nbsp/>generates<nbsp/>warning<nbsp/>assigning<nbsp/>to<nbsp/>constant
a.each<nbsp/>{<nbsp/>|b.meth|<nbsp/>}<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>invokes<nbsp/>meth=<nbsp/>in<nbsp/>object<nbsp/>b
sum<nbsp/>=<nbsp/>0
var<nbsp/>=<nbsp/>nil
a.each<nbsp/>{<nbsp/>|var|<nbsp/>sum<nbsp/>+=<nbsp/>var<nbsp/>}<nbsp/><nbsp/>#<nbsp/>uses<nbsp/>sum<nbsp/>and<nbsp/>var<nbsp/>from<nbsp/>enclosing<nbsp/>scope
</alltt>
</codefragment>
<p/>
If a local variable (including a block parameter) is first assigned in
a block, it is local to the block. If instead a variable of the same
name is already established at the time the block executes, the block
will inherit that variable.
<p/>
A block takes on the set of local variables in existence at the time
that it is created. This forms part of its binding.
Note that
although the binding of the variables is fixed at this point, the
block will have access to the <em>current</em> values of these variables
when it executes. The binding preserves these variables even if the
original enclosing scope is destroyed.
<p/>
The bodies of <kw>while</kw>, <kw>until</kw>, and <kw>for</kw> loops are part of
the scope that contains them; previously existing locals can be used
in the loop, and any new locals created will be available outside the
bodies afterward.
<subsection>Predefined Variables</subsection>  Predefined Variables
<p/>
The following variables are predefined in the Ruby interpreter. In
these descriptions, the notation {<sansfont></sansfont>} indicates that the variables
are read-only; an error will be raised if a program attempts to modify
a read-only variable.
After all, you probably don't want to change the
meaning of <const>true</const> halfway through your program (except perhaps
if you're a politician).  Entries marked {<sansfont></sansfont>} are thread local.
<p/>
Many global variables look something like Snoopy swearing: <var>$_</var>,
<var>$!</var>, <var>$&amp;</var>, and so on. This is for ``historical'' reasons,
as most of these variable names come from Perl. If you find memorizing
all this punctuation difficult, you might want to have a look at the
library file called ``English,''
documented
on page 445, which gives the commonly used global variables
more descriptive names.
<p/>
In the tables of variables and constants that follow, we show the
variable name, the type of the referenced object, and a description.
<subsubsection>Exception Information</subsubsection>
<p/>
<variable name="$!" type="Exception">The exception object passed to <tt>raise</tt>.  
  {<sansfont></sansfont>}</variable>
<p/>
<variable name="$@" type="Array">The stack backtrace generated by the last
                    exception. See <mim><file>kernel</file><front>Kernel</front><back>caller</back><mref>caller</mref></mim>
                     on page 413 for details. {<sansfont></sansfont>}</variable>
<subsubsection>Pattern Matching Variables</subsubsection>
<p/>
These variables (except <var>$=</var>) are set to <tt>nil</tt> after an
unsuccessful pattern match.
<p/>
<variable name="$&amp;" type="String">The string matched by the last successful pattern
                   match. This variable is local to the current
                   scope. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$+" type="String">The contents of the highest-numbered group matched
                   in the last successful pattern match. Thus, in
                   <tt>"cat" =~/(c|a)(t|z)/</tt>, <tt>$+</tt> will be set to 
                   ``t''.  This variable is local to the current
                   scope. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$`" type="String">The string preceding the match in the last
                   successful pattern match. This variable is local to 
                   the current scope. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$'" type="String">The string following the match in the last
                   successful pattern match. This variable is local to 
                   the current scope. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$=" type="Object">If set to any value apart from <tt>nil</tt> or
                   <const>false</const>, all pattern matches will be case
                   insensitive, string comparisons will ignore case,
                   and string hash values will be case insensitive.</variable>
<p/>
<variable name="$1 to $9" type="String">                   The contents of successive groups matched in the
                   last successful pattern match.  In
                   <tt>"cat" =~/(c|a)(t|z)/</tt>, <tt>$1</tt> will be set to 
                   ``a'' and <tt>$2</tt> to ``t''.  This variable is
                   local to the current scope. {<sansfont></sansfont>}</variable>
<variable name="$~" type="MatchData">An object that encapsulates the results of a
                   successful pattern match. The variables <tt>$&amp;</tt>,
                   <tt>$`</tt>, <tt>$'</tt>, and <tt>$1</tt> to <tt>$9</tt> are all
                   derived from <tt>$~</tt>. Assigning to <tt>$~</tt>
                   changes the values of these derived
                   variables.  This variable is local to the current
                   scope. {<sansfont></sansfont>}</variable>
<subsubsection>Input/Output Variables</subsubsection>
<p/>
<variable name="$/" type="String">The input record separator (newline by
                   default). This is the value that routines such as
                   <mim><file>kernel</file><front>Kernel</front><back>gets</back><mref>gets</mref></mim> use to determine record
                   boundaries. If set to <tt>nil</tt>, <meth>gets</meth> will read 
                   the entire file.</variable>
<p/>
<variable name="$-0" type="String">Synonym for <var>$/</var>.</variable>
<p/>
<variable name="$\" type="String">The string appended to the output of every call to methods such
                   as <mim><file>kernel</file><front>Kernel</front><back>print</back><mref>print</mref></mim> and <cim><file>io</file><front>IO</front><back>write</back><mref>write</mref></cim>. The
                   default value is <tt>nil</tt>.</variable>
<p/>
<variable name="$," type="String">The separator string output between the parameters to
                   methods such as <mim><file>kernel</file><front>Kernel</front><back>print</back><mref>print</mref></mim> and
                   <cim><file>array</file><front>Array</front><back>join</back><mref>join</mref></cim>. Defaults to <tt>nil</tt>, which adds no text.</variable>
<p/>
<variable name="$." type="Fixnum">The number of the last line read from the current
                   input file.</variable>
<p/>
<variable name="$;" type="String">The default separator pattern used by <cim><file>string</file><front>String</front><back>split</back><mref>split</mref></cim>.
                   May be set from the command line using the
                   <cmdopt>-F</cmdopt>                   
                   flag.</variable>
<p/>
<variable name="$&lt;" type="Object">An object that provides access to the concatenation
                   of the contents of all the files
                   given as command-line arguments, or <var>$stdin</var>
                   (in the case where there are no
                   arguments). <var>$&lt;</var> supports methods similar to a 
                   <classname>File</classname> object:
                   <meth>binmode</meth>, <meth>close</meth>,
                   <meth>closed?</meth>, <meth>each</meth>,
                   <meth>each_byte</meth>, <meth>each_line</meth>,
                   <meth>eof</meth>, <meth>eof?</meth>, <meth>file</meth>,
                   <meth>filename</meth>, <meth>fileno</meth>,
                   <meth>getc</meth>, <meth>gets</meth>, <meth>lineno</meth>,
                   <meth>lineno=</meth>, <meth>pos</meth>, <meth>pos=</meth>,
                   <meth>read</meth>, <meth>readchar</meth>,
                   <meth>readline</meth>, <meth>readlines</meth>,
                   <meth>rewind</meth>, <meth>seek</meth>, <meth>skip</meth>,
                   <meth>tell</meth>, <meth>to_a</meth>, <meth>to_i</meth>,
                   <meth>to_io</meth>, <meth>to_s</meth>, along with the
                   methods in <modulename>Enumerable</modulename>. The method <meth>file</meth> 
                   returns a <classname>File</classname> object for the file currently
                   being read. This may change as <var>$&lt;</var> reads
                   through the files on the command line. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$&gt;" type="IO">The destination of output for <mim><file>kernel</file><front>Kernel</front><back>print</back><mref>print</mref></mim>
                   and <mim><file>kernel</file><front>Kernel</front><back>printf</back><mref>printf</mref></mim>. The default value is
                   <var>$stdout</var>.</variable>
<p/>
<variable name="$_" type="String">The last line read by <mim><file>kernel</file><front>Kernel</front><back>gets</back><mref>gets</mref></mim> or
                   <mim><file>kernel</file><front>Kernel</front><back>readline</back><mref>readline</mref></mim>. Many string-related
                   functions in the <modulename>Kernel</modulename> module operate on <var>$_</var>
                   by default. The variable is local to the current
                   scope. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$defout" type="IO">Synonym for <var>$&gt;</var>.</variable>
<p/>
<variable name="$-F" type="String">Synonym for <tt>$;</tt>.</variable>
<p/>
<variable name="$stderr" type="IO">The current standard error output.</variable>
<p/>
<variable name="$stdin" type="IO">The current standard input.</variable>
<p/>
<variable name="$stdout" type="IO">The current standard output.</variable>
<subsubsection>Execution Environment Variables</subsubsection>
<p/>
<variable name="$0" type="String">The name of the top-level Ruby program being
                   executed.                   
                   Typically this will be the program's
                   filename. On some operating systems, assigning to
                   this variable will change the name of the process
                   reported (for example) by the <tt>ps(1)</tt> command.</variable>
<p/>
<variable name="$*" type="Array">An array of strings containing the command-line
                   options from the invocation of the program. Options
                   used by the Ruby interpreter will have been
                   removed. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$&#34;" type="Array">An array containing the filenames of modules
                   loaded by
                   <meth>require</meth>.
                   {<sansfont></sansfont>}</variable>
<p/>
<variable name="$$" type="Fixnum">The process number of the program being
                   executed. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$?" type="Fixnum">The exit status of the last child process to
                   terminate. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$:" type="Array">An array of strings, where each string specifies a
                   directory to be searched for Ruby scripts and
                   binary extensions used by the <meth>load</meth> and
                   <meth>require</meth> methods.                                      
                   The initial value is the 
                   value of the arguments passed via the <cmdopt>-I</cmdopt>                   
                   command-line option, followed by an
                   installation-defined standard library location, followed by the
                   current directory (``.''). This variable may be set 
                   from within a program to alter the default search
                   path; typically, programs use <tt>$:<nbsp/>&lt;&lt;<nbsp/>dir</tt> to
                   append <tt>dir</tt> to the path. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$-a" type="Object">True if the <cmdopt>-a</cmdopt> option is specified on the 
                   command line. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$-d" type="Object">Synonym for <var>$DEBUG</var>.</variable>
<p/>
<variable name="$DEBUG" type="Object">Set to <const>true</const> if the <cmdopt>-d</cmdopt> command-line 
                   option is specified.</variable>
<p/>
<variable name="__FILE__" type="String">The name of the current source file. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$F" type="Array">The array that receives the split input line if the
  <cmdopt>-a</cmdopt> command-line option is used.</variable>
<p/>
<variable name="$FILENAME" type="String">The name of the current input file. Equivalent to
                   <tt>$&lt;.filename</tt>. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$-i" type="String">If in-place edit mode is enabled (perhaps using the 
                   <cmdopt>-i</cmdopt>                   
                   command-line option), <var>$-i</var> holds
                   the extension used when creating the backup
                   file. If you set a value into <var>$-i</var>, enables
                   in-place edit mode. See page 136.</variable>
<p/>
<variable name="$-I" type="Array">Synonym for <var>$:</var>. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$-K" type="String">Sets the multibyte coding system for strings and
                   regular expressions. Equivalent to the
                   <cmdopt>-K</cmdopt>                   
                   command-line option. See page
                   137.</variable>
<p/>
<variable name="$-l" type="Object">Set to <const>true</const> if the <cmdopt>-l</cmdopt> option
                   (which enables line-end processing) is present on
                   the command line. See page
                   137. {<sansfont></sansfont>}</variable>
<p/>
<variable name="__LINE__" type="String">The current line number in the source
                          file. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$LOAD_PATH" type="Array">A synonym for <var>$:</var>. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$-p" type="Object">Set to <const>true</const> if the <cmdopt>-p</cmdopt> option
                   (which puts an implicit <tt>while<nbsp/>gets</tt> ...
                   <tt>end</tt> loop around your program) is present on
                   the command line. See page
                   137. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$SAFE" type="Fixnum">The current safe level (see page
                   254). This variable's value may
                   never be reduced by assignment. {<sansfont></sansfont>}</variable>
<p/>
<variable name="$VERBOSE" type="Object">                   Set to <const>true</const> if the <cmdopt>-v</cmdopt>,                   
                   <cmdopt>--version</cmdopt>, or
                   <cmdopt>-w</cmdopt>  option is
                   specified on the command line. Setting this option
                   to <const>true</const> causes the interpreter and some
                   library routines to report additional
                   information.</variable>
<p/>
<variable name="$-v" type="Object">Synonym for <var>$VERBOSE</var>.</variable>
<p/>
<variable name="$-w" type="Object">Synonym for <var>$VERBOSE</var>.</variable>
<subsubsection>Standard Objects</subsubsection>
<p/>
<variable name="ARGF" type="Object">A synonym for <var>$&lt;</var>.</variable>
<p/>
<variable name="ARGV" type="Array">A synonym for <var>$*</var>.</variable>
<p/>
<variable name="ENV" type="Object">A hash-like object containing the program's
  environment variables. An instance of class <classname>Object</classname>,
  <tt>ENV</tt> implements the full set of <classname>Hash</classname> methods. Used 
  to query and set the value of an environment variable, as in
  <tt>ENV["PATH"]</tt> and <tt>ENV['term']="ansi"</tt>.</variable>
<p/>
<variable name="false" type="FalseClass">Singleton instance of class <classname>FalseClass</classname>. {<sansfont></sansfont>}</variable>
<p/>
<variable name="nil" type="NilClass">The singleton instance of class
  <classname>NilClass</classname>. The value of uninitialized
  instance and global variables. {<sansfont></sansfont>}</variable>
<p/>
<variable name="self" type="Object">The receiver (object) of the current method. {<sansfont></sansfont>}</variable>
<p/>
<variable name="true" type="TrueClass">Singleton instance of class <classname>TrueClass</classname>. {<sansfont></sansfont>}</variable>
<subsection>Global Constants</subsection>
<p/>
The following constants are defined by the Ruby interpreter.
<p/>
<variable name="DATA" type="IO">If the the main program file contains the directive
  <tt>__END__</tt>,  
  then the constant <const>DATA</const>
  will be initialized so that reading from it will return lines
  following <tt>__END__</tt> from the source file.</variable>
<p/>
<variable name="FALSE" type="FalseClass">Synonym for <tt>false</tt>.</variable>
<p/>
<variable name="NIL" type="NilClass">Synonym for <tt>nil</tt>.</variable>
<p/>
<variable name="RUBY_PLATFORM" type="String">The identifier of the platform running
  this program. This string is in the same form as the platform
  identifier used by the GNU configure utility (which is not a
  coincidence).</variable>
<p/>
<variable name="RUBY_RELEASE_DATE" type="String">The date of this release.</variable>
<p/>
<variable name="RUBY_VERSION" type="String">The version number of the interpreter.</variable>
<p/>
<variable name="STDERR" type="IO">The actual standard error stream for the program. The
  initial value of <var>$stderr</var>.</variable>
<p/>
<variable name="STDIN" type="IO">The actual standard input stream for the program. The
  initial value of <var>$stdin</var>.</variable>
<p/>
<variable name="STDOUT" type="IO">The actual standard output stream for the program. The
  initial value of <var>$stdout</var>.</variable>
<p/>
<variable name="TOPLEVEL_BINDING" type="Binding">A <classname>Binding</classname> object representing
  the binding at Ruby's top level---the level where programs are
  initially executed.</variable>
<p/>
<variable name="TRUE" type="TrueClass">Synonym for <tt>true</tt>.</variable>
<section>Expressions</section>
<subsection>Single Terms</subsection>
<p/>
Single terms in an expression may be any of the following.
<p/>
<ul>
<p/>
<li> <b>Literal</b>. Ruby literals are numbers, strings, arrays,
  hashes, ranges, symbols, and regular expressions. There are
  described starting on page 201.
<p/>
</li><li> <b>Shell Command</b>.  A shell command is a string enclosed
  in backquotes, or in a general delimited string (page
  200) starting with
  <tt>%x</tt>.  
  The value of the string is the standard
  output of running the command represented by the string under the
  host operating system's standard shell. The execution also sets the
  <var>$?</var> variable with the command's exit status.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    filter = "*.c"
    files = `ls #{filter}`
    files = %x{ls #{filter}}
]]></fullcode>
filter<nbsp/>=<nbsp/>"*.c"
files<nbsp/>=<nbsp/>`ls<nbsp/>#{filter}`
files<nbsp/>=<nbsp/>%x{ls<nbsp/>#{filter}}
</alltt>
</codefragment>
<p/>
</li><li> <b>Symbol Generator</b>. A <classname>Symbol</classname> object is created by
  prefixing an operator, variable, constant, method, class, or module
  name with a colon.  
  The symbol object will be unique for each
  different name but does not refer to a particular instance of the
  name, so the symbol for (say) <tt>:fred</tt> will be the same regardless
  of context. A symbol is similar to the concept of atoms in other
  high-level languages.
<p/>
</li><li> <b>Variable Reference</b> or <b>Constant Reference</b>. A variable
  is referenced by citing its name. Depending on scope (see page
  211), a constant is referenced either by citing its
  name or by qualifying the name, using the name of the class or
  module containing the constant and the scope operator
  (``<tt>::</tt>'').  
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    barney    # variable reference
    APP_NAMR  # constant reference
    Math::PI  # qualified constant reference
]]></fullcode>
barney<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>variable<nbsp/>reference
APP_NAMR<nbsp/><nbsp/>#<nbsp/>constant<nbsp/>reference
Math::PI<nbsp/><nbsp/>#<nbsp/>qualified<nbsp/>constant<nbsp/>reference
</alltt>
</codefragment>
<p/>
</li><li> <b>Method Invocation</b>. The various ways of invoking a
  method are described starting on page 227.
</li></ul>
<subsection>Operator Expressions</subsection>
<p/>
<figure type="table">
      <caption>Ruby operators (high to low
    precedence)</caption>  
  <table>
<th>
  <td><b>Method</b></td>
  <td><b>Operator</b></td>
  <td><b>Description</b></td>
</th>
<tr>
  <td>Y</td>
  <td><tt>[ ]</tt><nbsp/>0<tt>[ ]=</tt></td>
  <td>Element reference, element set</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>**</tt></td>
  <td>Exponentiation</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>!</tt><nbsp/>0<tt>~</tt><nbsp/>0<tt>+</tt><nbsp/>0<tt>--</tt></td>
  <td>Not, complement,
     unary plus and minus (method names for the last two are
     <tt>+@</tt> and <tt>-@</tt>)</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>*</tt><nbsp/>0<tt>/</tt><nbsp/>0<tt>%</tt></td>
  <td>Multiply, divide, and modulo</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>+</tt><nbsp/>0<tt>--</tt></td>
  <td>Plus and minus</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>&gt;&gt;</tt><nbsp/>0<tt>&lt;&lt;</tt></td>
  <td>Right and left shift</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>&amp;</tt></td>
  <td>Bitwise `and'</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>^</tt><nbsp/>0<tt>|</tt></td>
  <td>Bitwise exclusive `or' and regular `or'</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>&lt;=</tt><nbsp/>0<tt>&lt;</tt><nbsp/>0<tt>&gt;</tt><nbsp/>0<tt>&gt;=</tt></td>
  <td>Comparison operators</td>
</tr>
<tr>
  <td>Y</td>
  <td><tt>&lt;=&gt;</tt><nbsp/>0<tt>==</tt><nbsp/>0<tt>===</tt><nbsp/>0<tt>!=</tt><nbsp/>0<tt>=~</tt><nbsp/>0<tt>!~</tt></td>
  <td>Equality and pattern match operators (<tt>!=</tt> and
           <tt>!~</tt> may not be defined as methods)</td>
</tr>
<tr>
  <td></td>
  <td><tt>&amp;&amp;</tt></td>
  <td>Logical `and'</td>
</tr>
<tr>
  <td></td>
  <td><tt>||</tt></td>
  <td>Logical `or'</td>
</tr>
<tr>
  <td></td>
  <td><tt>..</tt><nbsp/>0<tt>...</tt></td>
  <td>Range (inclusive and exclusive)</td>
</tr>
<tr>
  <td></td>
  <td><tt>? :</tt></td>
  <td>Ternary if-then-else</td>
</tr>
<tr>
  <td></td>
  <td><tt>=</tt><nbsp/>0<tt>%=</tt><nbsp/>0<tt></tt>{ <tt>/=</tt><nbsp/>0<tt>--=</tt><nbsp/>0<tt>+=</tt><nbsp/>0<tt>|=</tt> <tt>&amp;=</tt><nbsp/>0<tt>&gt;&gt;=</tt><nbsp/>0<tt>&lt;&lt;=</tt><nbsp/>0<tt>*=</tt><nbsp/>0<tt>&amp;&amp;=</tt><nbsp/>0<tt>||=</tt><nbsp/>0<tt>**=</tt></td>
  <td>Assignment</td>
</tr>
<tr>
  <td></td>
  <td><kw>defined?</kw></td>
  <td>Check if symbol defined</td>
</tr>
<tr>
  <td></td>
  <td><kw>not</kw></td>
  <td>Logical negation</td>
</tr>
<tr>
  <td></td>
  <td><kw>or</kw><nbsp/>0<kw>and</kw></td>
  <td>Logical composition</td>
</tr>
<tr>
  <td></td>
  <td><kw>if</kw><nbsp/>0<kw>unless</kw><nbsp/>0<kw>while</kw><nbsp/>0<kw>until</kw></td>
  <td>Expression modifiers</td>
</tr>
<tr>
  <td></td>
  <td><kw>begin/end</kw></td>
  <td>Block expression</td>
</tr>
<bottomrule/></table>
<p/>
</figure>
<p/>
Expressions may be combined using operators.  Table
18.4 on page 219 lists the Ruby operators in precedence order. The
operators with a Y in the <em>method</em> column are implemented as
methods, and may be overridden.
<subsection>More on Assignment</subsection>
<p/>
The assignment operator assigns one or more <em>rvalues</em> to one or
more <em>lvalues</em>. What is meant by assignment depends on each
individual lvalue.
<p/>
If an lvalue is a variable or constant name, that variable or constant 
receives a reference to the corresponding rvalue.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a, b, c = 1, "cat", [ 3, 4, 5 ]
]]></fullcode>
a,<nbsp/>b,<nbsp/>c<nbsp/>=<nbsp/>1,<nbsp/>"cat",<nbsp/>[<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>]
</alltt>
</codefragment>
<p/>
If the lvalue is an object attribute, the corresponding attribute
setting method will be called in the receiver, passing as a parameter
the rvalue.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    class A
!-      attr_writer :value
!-    end
  anObj = A.new
  anObj.value = "hello"   # equivalent to anObj.value=("hello")
]]></fullcode>
anObj<nbsp/>=<nbsp/>A.new
anObj.value<nbsp/>=<nbsp/>"hello"<nbsp/><nbsp/><nbsp/>#<nbsp/>equivalent<nbsp/>to<nbsp/>anObj.value=("hello")
</alltt>
</codefragment>
<p/>
If the lvalue is an array element reference, Ruby calls the element
assignment operator (``<tt>[]=</tt>'') in the receiver, passing as
parameters any indices that appear between the brackets followed by
the rvalue.  This is illustrated in Table 18.5 on page 220.
<p/>
<figure type="table">
  <caption>Mapping from element reference to method call</caption>
<center>
<p/>
  <table>
<th>
  <td><b>Element Reference</b></td>
  <td><b>Actual Method Call</b></td>
</th>
<tr>
  <td><tt>anObj[]  = "one"</tt></td>
  <td><tt>anObj.[]=("one")</tt></td>
</tr>
<tr>
  <td><tt>anObj[1] = "two"</tt></td>
  <td><tt>anObj.[]=(1, "two")</tt></td>
</tr>
<tr>
  <td><tt>anObj["a", /^cat/] = "three"</tt></td>
  <td><tt>anObj.[]=("a", /^cat/, "three")</tt></td>
</tr>
<bottomrule/></table>
<p/>
</center>
</figure>
<p/>
<subsubsection>Parallel Assignment</subsubsection>
<p/>
An assignment expression may have one or more lvalues and one or more 
rvalues. This section explains how Ruby handles assignment with
different combinations of arguments.
<p/>
<ol>
<li> If the last rvalue is prefixed with an asterisk and is
  an object of class <classname>Array</classname>, the rvalue is replaced
  with the elements of the array, with each element forming its own
  rvalue.
</li><li> If the assignment contains multiple lvalues and one rvalue, the
  rvalue is converted into an <classname>Array</classname>, and this array is expanded into a
  set of rvalues as described in (1).
</li><li> Successive rvalues are assigned to the lvalues. This assignment
  effectively happens in parallel, so that (for example) <tt>a,b=b,a</tt>
  swaps the values in ``a'' and ``b.''
</li><li> If there are more lvalues than rvalues, the excess will have
  <tt>nil</tt> assigned to them.
</li><li> If there are more rvalues that lvalues, the excess will be
  ignored.
</li><li> These rules are modified slightly if the last lvalue is preceded
  with an asterisk. This lvalue will always receive an array during
  the assignment. The array will consist of whatever rvalue would
  normally have been assigned to this lvalue, followed by the excess
  rvalues (if any).
</li><li> If an lvalue is a parenthesized list, it is treated as a nested
  assignment statement, and the list is assigned from the
  corresponding rvalue as described by these rules.
</li></ol>
<p/>
The tutorial has examples starting on page 75.
<subsection>Block Expressions</subsection>
<p/>
<syntax>
begin
  <nt>body</nt>
end
</syntax>
<p/>
Expressions may be grouped between <kw>begin</kw> and <kw>end</kw>.
The value of the block expression is the value of the last expression
executed.
<p/>
Block expressions also play a role in exception handling, which is discussed
starting on page 235.
<subsection>Boolean Expressions</subsection>  Boolean Expressions
<p/>
Boolean expressions evaluate to a truth value. Some Ruby constructs
(particularly ranges) behave differently when evaluated in a boolean
expression.
<subsubsection>Truth Values</subsubsection>
<p/>
Ruby predefines the globals <const>false</const> and <const>nil</const>. Both of these
values are treated as being false in a boolean context. All other
values are treated as being true.
<subsubsection>And, Or, Not, and Defined?</subsubsection>
<p/>
The <kw>and</kw> and <tt>&amp;&amp;</tt> operators evaluate their first operand. If
false, the expression returns false; otherwise, the expression returns
the value of the second operand.
<p/>
<syntax>
<nt>expr1</nt>  and  <nt>expr2</nt>
<nt>expr1</nt>  &amp;&amp;   <nt>expr2</nt>
</syntax>
<p/>
The <kw>or</kw> and <tt>||</tt> operators evaluate their first operand. If
true, the expression returns true; otherwise, the expression returns
the value of the second operand.
<p/>
<syntax>
<nt>expr1</nt>  or  <nt>expr2</nt>
<nt>expr1</nt>  ||  <nt>expr2</nt>
</syntax>
<p/>
The <kw>not</kw> and <kw>!</kw> operators evaluate their operand. If true, the 
expression returns false. If false, the expression returns true.
<p/>
The word forms of these operators (<kw>and</kw>, <kw>or</kw>, and <kw>not</kw>) have
a lower precedence than the corresponding symbol forms (<kw>&amp;&amp;</kw>,
<kw>||</kw>, and <kw>!</kw>). See Table 18.4 on page 219 for details.
<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. For examples, see page
78 in the tutorial.
<subsubsection>Comparison Operators</subsubsection>
<p/>
The Ruby syntax defines the comparison operators <tt>==</tt>, <tt>===</tt>,
<tt>&lt;=&gt;</tt>, <tt>&lt;</tt>, <tt>&lt;=</tt>, <tt>&gt;</tt>, <tt>&gt;=</tt>, <tt>=~</tt>, and the standard 
methods <tt>eql?</tt> and
<tt>equal?</tt> (see Table 7.1 on page 79). All of these operators
are implemented as methods. 
Although the operators have intuitive meaning,
it is up to the classes that implement them to produce meaningful
comparison semantics. The library reference starting
on page 275 describes the comparison semantics for the
built-in classes. The module <modulename>Comparable</modulename> provides support for
implementing the operators <tt>==</tt>, 
<tt>&lt;</tt>, <tt>&lt;=</tt>, <tt>&gt;</tt>, <tt>&gt;=</tt>, and the method <meth>between?</meth> in terms of <tt>&lt;=&gt;</tt>.
The operator <tt>===</tt> is used in <kw>case</kw> expressions, described
on page 223. 
<p/>
Both <tt>==</tt> and <tt>=~</tt> have negated forms, <tt>!=</tt> and
<tt>!~</tt>. Ruby converts these during syntax analysis:
<tt>a!=b</tt> is mapped to <tt>!(a==b)</tt>, and <tt>a!~b</tt>
is mapped to <tt>!(a<nbsp/>=~b)</tt>. There are no methods corresponding to
<tt>!=</tt> and <tt>!~</tt>.
<subsubsection>Ranges in Boolean Expressions</subsubsection>
<p/>
<syntax>
if  <nt>expr1</nt> .. <nt>expr2</nt>
while  <nt>expr1</nt> ... <nt>expr2</nt>
</syntax>
<p/>
A range used in a boolean expression acts as a flip-flop.
It has two
states, set and unset, and is initially unset. On each call, the range
cycles through the state machine shown in Figure 18.1 on page 223.
The range returns <const>true</const> if it is in the set state at the end of
the call, and <const>false</const> otherwise.
<p/>
The two-dot form of a range behaves slightly differently than the
three-dot form. When the two-dot form first makes the transition from
unset to set, it immediately evaluates the end condition and makes
the transition accordingly. This means that if <em>expr1</em> and
<em>expr2</em> both evaluate to <const>true</const> on the same call, the
two-dot form will finish the call in the unset state. However, it
still returns <const>true</const> for this call.
<p/>
The difference is illustrated by the following code:
<p/>
<codefragment>
<fullcode><![CDATA[a = (11..20).collect {|i| (i%4 == 0)..(i%3 == 0) ? i : nil}
a

a = (11..20).collect {|i| (i%4 == 0)...(i%3 == 0) ? i : nil}
a  
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>(11..20).collect<nbsp/>{|i|<nbsp/>(i%4<nbsp/>==<nbsp/>0)..(i%3<nbsp/>==<nbsp/>0)<nbsp/>?<nbsp/>i<nbsp/>:<nbsp/>nil}</tt></td>
</tr>
<tr>
  <td><tt>a</tt></td>
  <td>&#187;</td>
  <td><tt>[nil,<nbsp/>12,<nbsp/>nil,<nbsp/>nil,<nbsp/>nil,<nbsp/>16,<nbsp/>17,<nbsp/>18,<nbsp/>nil,<nbsp/>20]</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>(11..20).collect<nbsp/>{|i|<nbsp/>(i%4<nbsp/>==<nbsp/>0)...(i%3<nbsp/>==<nbsp/>0)<nbsp/>?<nbsp/>i<nbsp/>:<nbsp/>nil}</tt></td>
</tr>
<tr>
  <td><tt>a</tt></td>
  <td>&#187;</td>
  <td><tt>[nil,<nbsp/>12,<nbsp/>13,<nbsp/>14,<nbsp/>15,<nbsp/>16,<nbsp/>17,<nbsp/>18,<nbsp/>nil,<nbsp/>20]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
<subsubsection>Regular Expressions in Boolean Expressions</subsubsection>
<p/>
If a single regular expression appears as a boolean expression, it is
matched against the current value of the variable <var>$_</var>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  if /re/ ...
]]></fullcode>
if<nbsp/>/re/<nbsp/>...
</alltt>
</codefragment>
is equivalent to
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  if $_ =~ /re/ ...
]]></fullcode>
if<nbsp/>$_<nbsp/>=~<nbsp/>/re/<nbsp/>...
</alltt>
</codefragment>
<subsection>If and Unless Expressions</subsection>  <tt>if</tt> and <tt>unless</tt> Expressions
<p/>
<syntax>
if <nt>boolean-expression</nt> <opt>then</opt>
  <nt>body</nt>
elsif <nt>boolean-expression</nt> <opt>then</opt>
  <nt>body</nt>
else
  <nt>body</nt>
end
</syntax>
<p/>
<syntax>
unless <nt>boolean-expression</nt> <opt>then</opt>
  <nt>body</nt>
else
  <nt>body</nt>
end
</syntax>
<p/>
The <kw>then</kw>  keyword separates the body from the condition.
It is
not required if the body starts on a new line.
The value of an <kw>if</kw> or <kw>unless</kw> expression is the value of the
last expression evaluated in whichever body is executed.
<subsubsection>If and Unless Modifiers</subsubsection>
<p/>
<syntax>
<nt>expression</nt> if     <nt>boolean-expression</nt>
<nt>expression</nt> unless <nt>boolean-expression</nt>
</syntax>
<p/>
evaluates <em>expression</em> only if <em>boolean-expression</em> is
<const>true</const> (<const>false</const> for <kw>unless</kw>).
<subsection>Ternary Operator</subsection>
<p/>
<syntax>
<nt>boolean-expression</nt> ? <nt>expr1</nt> : <nt>expr2</nt>
</syntax>
<p/>
returns <em>expr1</em> if <em>boolean expression</em> is true and
<em>expr2</em> otherwise.
<subsection>Case Expressions</subsection>  <tt>case</tt> Expressions
<p/>
<syntax>
case <nt>target</nt>
  when <optn><nt>comparison</nt></optn> <opt>then</opt>
    <nt>body</nt>
  when <optn><nt>comparison</nt></optn> <opt>then</opt>
    <nt>body</nt>
  ...
<opt> else
    <nt>body</nt> </opt>
 end
</syntax>
<p/>
A case expression
searches for a match by starting at the first (top left) comparison,
performing <em>comparison</em><nbsp/><tt>===</tt><nbsp/><em>target</em>.
When a comparison
returns true, the search stops, and the body associated with the
comparison is executed. <kw>case</kw> then returns the value of the last
expression executed.  If no <em>comparison</em> matches: if an <kw>else</kw>
clause is present, its body will be executed; otherwise, <kw>case</kw>
silently returns <tt>nil</tt>.
<p/>
The <kw>then</kw> keyword separates the <kw>when</kw> comparisons from the
bodies, and is not needed if the body starts on a new line.
<subsection>Loops</subsection>  Loop Constructs
<p/>
<syntax>
while <nt>boolean-expression</nt> <opt>do</opt>
  <nt>body</nt>
end
</syntax>
<p/>
executes <em>body</em> zero or more times as long as
<em>boolean-expression</em> is true.
<p/>
<syntax>
until <nt>boolean-expression</nt> <opt>do</opt>
  <nt>body</nt>
end
</syntax>
<p/>
executes <em>body</em> zero or more times as long as
<em>boolean-expression</em> is false.
<p/>
In both forms, the <kw>do</kw> separates <em>boolean-expression</em> from
the <em>body</em>, and may be omitted when the body starts on a new
line.
<p/>
<syntax>
for <optn><nt>name</nt></optn> in <nt>expression</nt> <opt>do</opt>
  <nt>body</nt>
end
</syntax>
<p/>
The <kw>for</kw> loop is executed as if it were the following
<meth>each</meth> loop, except that local variables defined in the body of 
the <kw>for</kw> loop will be available outside the loop, while those
defined within an iterator block will not.
<p/>
<syntax>
<nt>expression</nt>.each do | <optn><nt>name</nt></optn> |
  <nt>body</nt>
end
</syntax>
<p/>
<meth>loop</meth>,
which iterates its associated block, is not
a language construct---it is a method in module <modulename>Kernel</modulename>.
<subsubsection>While and Until Modifiers</subsubsection>
<p/>
<syntax>
<nt>expression</nt> while <nt>boolean-expression</nt>
<nt>expression</nt> until <nt>boolean-expression</nt>
</syntax>
<p/>
If <em>expression</em> is anything other than a <kw>begin/end</kw> block,
executes <em>expression</em> zero or more times while <em>boolean-expression</em>
is <const>true</const> (<const>false</const> for <kw>until</kw>).
<p/>
If <em>expression</em> is a <kw>begin/end</kw> block, the block will always
be executed at least one time.
<subsection>Break, Redo, Next, and Retry</subsection>
<p/>
<kw>break</kw>, <kw>redo</kw>, <kw>next</kw>, and
<kw>retry</kw> alter the normal flow through a <kw>while</kw>, <kw>until</kw>,
<kw>for</kw>, or iterator controlled loop.
<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.
<kw>retry</kw> restarts the loop, reevaluating the condition.
<p/>
<section>Method Definition</section>
<p/>
<syntax>
  def <nt>defname</nt> <opt>( <optz><nt>arg</nt> <opt>=<nt>val</nt></opt></optz> <opt>, *<nt>vararg</nt></opt> <opt>, &amp;<nt>blockarg</nt></opt> )</opt>
    <nt>body</nt>
  end
</syntax>
<p/>
<nt>defname</nt> is both the name of the method and optionally the
context in which it is valid.
<p/>
<syntax>
<table>
<tr><td>
<nt>defname</nt> </td><td> &lt;-</td><td> <nt>methodname</nt> </td></tr><tr><td></td><td>        </td><td> <nt>expr</nt>.<nt>methodname</nt>
</td></tr></table>
</syntax>
<p/>
A <nt>methodname</nt> is either a redefinable operator (see Table
18.4 on page 219) or a name.
If <nt>methodname</nt> is a name, it
should start with a lowercase letter (or underscore) optionally
followed by upper- and lowercase letters, underscores, and digits. A
<nt>methodname</nt> may optionally end with a question mark (``<tt>?</tt>''),
exclamation point (``<tt>!</tt>''), or equals sign (``<tt>=</tt>''). The
question mark and exclamation point are simply part of the name. The
equals sign is also part of the name but additionally signals that
this method is an attribute setter (described
on page 23).
<p/>
A method definition using an unadorned method name within a class or
module definition creates an instance method. An instance method may
be invoked only by sending its name to a receiver that is an
instance of the class that defined it (or one of that class's subclasses).
<p/>
Outside a class or module definition, a definition with an unadorned
method name is added as a private method to class <classname>Object</classname>, and
hence may be called in any context without an explicit receiver.
<p/>
A definition using a method name of the form <nt>expr</nt>.<nt>methodname</nt>
creates a method associated with the object that is the value
of the expression; the method will be callable only by supplying the
object referenced by the expression as a receiver. Other Ruby
documentation calls these methods <em>singleton methods</em>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class MyClass
    def MyClass.method      # definition
    end
  end
]]></fullcode>
class<nbsp/>MyClass
<nbsp/><nbsp/>def<nbsp/>MyClass.method<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>definition
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class MyClass
!-    def MyClass.method      # definition
!-    end
!-  end
  MyClass.method            # call
  
  anObject = Object.new
  def anObject.method       # definition
  end
  anObject.method           # call

  def (1.class).fred        # receiver may be an expression
  end
  Fixnum.fred               # call
]]></fullcode>
MyClass.method<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>call
<p/>
anObject<nbsp/>=<nbsp/>Object.new
def<nbsp/>anObject.method<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>definition
end
anObject.method<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>call
<p/>
def<nbsp/>(1.class).fred<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>receiver<nbsp/>may<nbsp/>be<nbsp/>an<nbsp/>expression
end
Fixnum.fred<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>call
</alltt>
</codefragment>
<p/>
Method definitions may not contain class, module, or instance method
definitions. They may contain nested
singleton method definitions.
The body of a method acts as if it were
a <kw>begin</kw>/<kw>end</kw> block, in that it may contain exception handling
statements (<kw>rescue</kw>, <kw>else</kw>, and <kw>ensure</kw>).
<subsection>Method Arguments</subsection>
<p/>
A method definition may have zero or more regular arguments, an
optional array argument, and an optional block argument. Arguments are 
separated by commas, and the argument list may be enclosed in parentheses.
<p/>
A regular argument is a local variable name, optionally followed by an 
equals sign and an expression giving a default value.
The expression
is evaluated at the time the method is called. The expressions are
evaluated from left to right. An expression may reference a parameter that
precedes it in the argument list.
<p/>
<codefragment>
<fullcode><![CDATA[  def options(a=99, b=a+1)
    [ a, b ]
  end
  options
  options 1
  options 2, 4
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>options(a=99,<nbsp/>b=a+1)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>[<nbsp/>a,<nbsp/>b<nbsp/>]</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>options</tt></td>
  <td>&#187;</td>
  <td><tt>[99,<nbsp/>100]</tt></td>
</tr>
<tr>
  <td><tt>options<nbsp/>1</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>2]</tt></td>
</tr>
<tr>
  <td><tt>options<nbsp/>2,<nbsp/>4</tt></td>
  <td>&#187;</td>
  <td><tt>[2,<nbsp/>4]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The optional array argument must follow any regular arguments and may 
not have a default.
<p/>
When the method is invoked, Ruby sets the array
argument to reference a new
object of class <classname>Array</classname>. If the method call specifies any
parameters in excess of the regular argument count, all these extra
parameters will be collected into this newly created array.
<p/>
<codefragment>
<fullcode><![CDATA[  def varargs(a, *b)
    [ a, b ]
  end
  varargs 1
  varargs 1, 2
  varargs 1, 2, 3
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>varargs(a,<nbsp/>*b)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>[<nbsp/>a,<nbsp/>b<nbsp/>]</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>varargs<nbsp/>1</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>[]]</tt></td>
</tr>
<tr>
  <td><tt>varargs<nbsp/>1,<nbsp/>2</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>[2]]</tt></td>
</tr>
<tr>
  <td><tt>varargs<nbsp/>1,<nbsp/>2,<nbsp/>3</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>[2,<nbsp/>3]]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
If an array argument follows arguments with default values, parameters 
will first be used to override the defaults. The remainder will then
be used to populate the array.
<p/>
<codefragment>
<fullcode><![CDATA[  def mixed(a, b=99, *c)
    [ a, b, c]
  end
  mixed 1
  mixed 1, 2
  mixed 1, 2, 3
  mixed 1, 2, 3, 4
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>mixed(a,<nbsp/>b=99,<nbsp/>*c)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>[<nbsp/>a,<nbsp/>b,<nbsp/>c]</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>mixed<nbsp/>1</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>99,<nbsp/>[]]</tt></td>
</tr>
<tr>
  <td><tt>mixed<nbsp/>1,<nbsp/>2</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>2,<nbsp/>[]]</tt></td>
</tr>
<tr>
  <td><tt>mixed<nbsp/>1,<nbsp/>2,<nbsp/>3</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>2,<nbsp/>[3]]</tt></td>
</tr>
<tr>
  <td><tt>mixed<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>2,<nbsp/>[3,<nbsp/>4]]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The optional block argument must be the last in the list.
Whenever the method is called, Ruby checks for an associated block.
If a block is present,
it is converted to an object of class <classname>Proc</classname> and assigned
to the block argument. If no block is present, the argument is set to
<tt>nil</tt>.
<section>Invoking a Method</section>
<p/>
<syntax>
  <table>
<tr><td>
  <opt><nt>receiver</nt>. </opt> <nt>name</nt>  <opt> <nt>parameters</nt> </opt> <opt> <nt>block</nt> </opt></td></tr><tr><td><opt><nt>receiver</nt>::</opt> <nt>name</nt> <opt> <nt>parameters</nt> </opt> <opt> <nt>block</nt> </opt></td></tr><tr><td></td></tr><tr><td><nt>parameters</nt> </td><td> &lt;-</td><td> ( <optz><nt>param</nt></optz> <opt>, <nt>hashlist</nt></opt> <opt>*<nt>array</nt></opt> <opt>&amp;<nt>aProc</nt></opt> ) </td></tr><tr><td></td></tr><tr><td><nt>block</nt> </td><td> &lt;-</td><td> { <nt>blockbody</nt> }     </td></tr><tr><td></td><td>        </td><td> do <nt>blockbody</nt> end
  </td></tr></table>                      
</syntax>
<p/>
Initial parameters are assigned to the actual arguments of the
method.
Following these parameters may be a list of
<em>key</em><nbsp/><tt>=&gt;</tt><nbsp/><em>value</em> pairs. These pairs are collected into a
single new <classname>Hash</classname> object and passed as a single parameter.
<p/>
Following these parameters may be a single parameter prefixed with an
asterisk.
If this parameter is an array,
Ruby replaces it with zero 
or more parameters corresponding to the elements of the array.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Array
!-  def to_s
!-    inspect
!-  end
!-end
!-class Hash
!-  def to_s
!-    inspect
!-  end
!-end
  def regular(a, b, *c)
    # ..
  end
  regular 1, 2, 3, 4
  regular(1, 2, 3, 4)
  regular(1, *[2, 3, 4])
]]></fullcode>
def<nbsp/>regular(a,<nbsp/>b,<nbsp/>*c)
<nbsp/><nbsp/>#<nbsp/>..
end
regular<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4
regular(1,<nbsp/>2,<nbsp/>3,<nbsp/>4)
regular(1,<nbsp/>*[2,<nbsp/>3,<nbsp/>4])
</alltt>
</codefragment>
<p/>
A block may be associated with a method call using either a literal
block (which must start on the same source line as the last line of
the method call) or a parameter containing a reference to a <classname>Proc</classname>
or <classname>Method</classname> object prefixed with an ampersand character.
Regardless
of the presence of a block argument, Ruby arranges for the value of
the global function <mmm><file>kernel</file><front>Kernel</front><back>block_given?</back><mref>block_given_qm</mref></mmm>  to reflect the
availability of a block associated with the call.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Array
!-  def to_s
!-    inspect
!-  end
!-end
!-class Hash
!-  def to_s
!-    inspect
!-  end
!-end

  aProc   = proc { 99 }
  anArray = [ 98, 97, 96 ]
  
  def block
    yield
  end
  block { }
  block do
        end
  block(&aProc)

  def all(a, b, c, *d, &e)
    puts "a = #{a}"
    puts "b = #{b}"
    puts "c = #{c}"
    puts "d = #{d}"
    puts "block = #{yield(e)}"
  end

  all('test', 1 => 'cat', 2 => 'dog', *anArray, &aProc)
]]></fullcode>
<p/>
aProc<nbsp/><nbsp/><nbsp/>=<nbsp/>proc<nbsp/>{<nbsp/>99<nbsp/>}
anArray<nbsp/>=<nbsp/>[<nbsp/>98,<nbsp/>97,<nbsp/>96<nbsp/>]
<p/>
def<nbsp/>block
<nbsp/><nbsp/>yield
end
block<nbsp/>{<nbsp/>}
block<nbsp/>do
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
block(&amp;aProc)
<p/>
def<nbsp/>all(a,<nbsp/>b,<nbsp/>c,<nbsp/>*d,<nbsp/>&amp;e)
<nbsp/><nbsp/>puts<nbsp/>"a<nbsp/>=<nbsp/>#{a}"
<nbsp/><nbsp/>puts<nbsp/>"b<nbsp/>=<nbsp/>#{b}"
<nbsp/><nbsp/>puts<nbsp/>"c<nbsp/>=<nbsp/>#{c}"
<nbsp/><nbsp/>puts<nbsp/>"d<nbsp/>=<nbsp/>#{d}"
<nbsp/><nbsp/>puts<nbsp/>"block<nbsp/>=<nbsp/>#{yield(e)}"
end
<p/>
all('test',<nbsp/>1<nbsp/>=&gt;<nbsp/>'cat',<nbsp/>2<nbsp/>=&gt;<nbsp/>'dog',<nbsp/>*anArray,<nbsp/>&amp;aProc)
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
a<nbsp/>=<nbsp/>test
b<nbsp/>=<nbsp/>{1=&gt;"cat",<nbsp/>2=&gt;"dog"}
c<nbsp/>=<nbsp/>98
d<nbsp/>=<nbsp/>[97,<nbsp/>96]
block<nbsp/>=<nbsp/>99
</alltt>
</codefragment>
<p/>
A method is called by passing its name to a receiver. If no receiver
is specified, <var>self</var> is assumed.
<p/>
The receiver checks for the
method definition in its own class and then sequentially in its
ancestor classes. The instance methods of included modules act as if
they were in anonymous superclasses of the class that includes them.
If the method is not found, Ruby invokes the method
<meth>method_missing</meth> in the receiver. The default behavior
defined in <mmm><file>kernel</file><front>Kernel</front><back>method_missing</back><mref>method_missing</mref></mmm> is to report an error and
terminate the program.
<p/>
When a receiver is explicitly specified in a method invocation, it may
be separated from the method name using either a period ``<tt>.</tt>'' or
two colons ``<tt>::</tt>''.
The only difference between these two forms
occurs if the method name starts with an uppercase letter. In this
case, Ruby will assume that a <tt>receiver::Thing</tt> method call is
actually an attempt to access a constant called <tt>Thing</tt> in the
receiver <em>unless</em> the method invocation has a parameter list between
parentheses.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  Foo.Bar()         #  method call
  Foo.Bar           #  method call
  Foo::Bar()        #  method call
  Foo::Bar          #  constant access
]]></fullcode>
Foo.Bar()<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/><nbsp/>method<nbsp/>call
Foo.Bar<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/><nbsp/>method<nbsp/>call
Foo::Bar()<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/><nbsp/>method<nbsp/>call
Foo::Bar<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/><nbsp/>constant<nbsp/>access
</alltt>
</codefragment>
<p/>
The return value of a method is the value of the last expression
executed.
<p/>
<syntax>
return <optz><nt>expr</nt></optz>
</syntax>
<p/>
A <kw>return</kw> expression immediately exits a method. The value of a
<kw>return</kw> is <tt>nil</tt> if it is called with no parameters, the value of
its parameter if it is called with one parameter, or an array containing all of
its parameters if it is called with more than one parameter.
<subsection>super</subsection>
<p/>
<syntax>
super  <opt> ( <optz><nt>param</nt></optz> <opt>*<nt>array</nt></opt> ) </opt>  <opt><nt>block</nt></opt>
</syntax>
<p/>
Within the body of a method, a call to <kw>super</kw>
acts just like a
call to that original method, except that the search for a method body
starts in the superclass of the object that was found to contain the
original method. If no parameters (and no parentheses) are passed to
<kw>super</kw>, the original method's parameters will be passed; otherwise,
the parameters to <kw>super</kw> will be passed.
<subsection>Operator Methods</subsection>
<p/>
<syntax>
<nt>expr1</nt> <nt>operator</nt>
<nt>operator</nt> <nt>expr1</nt>
<nt>expr1</nt> <nt>operator</nt> <nt>expr2</nt>
</syntax>
<p/>
If the operator in an operator expression corresponds to a redefinable
method (see the Table 18.4 on page 219), Ruby will execute the 
operator expression as if it had been written
<p/>
<syntax>
(<nt>expr1</nt>).<nt>operator</nt>(<nt>expr2</nt>)
</syntax>
<subsection>Attribute Assignment</subsection>
<p/>
<syntax>
<nt>receiver</nt>.<nt>attrname</nt> = <nt>rvalue</nt>
</syntax>
<p/>
When the form <nt>receiver</nt>.<nt>attrname</nt> appears as an lvalue, Ruby
invokes a method named <nt>attrname=</nt> in the receiver, passing <nt>rvalue</nt> 
as a single parameter.
<subsection>Element Reference Operator</subsection>
<p/>
<syntax>
<nt>receiver <optn><nt>expr</nt></optn> </nt>
<nt>receiver <optn><nt>expr</nt></optn> </nt> = <nt>rvalue</nt>
</syntax>
<p/>
When used as an rvalue, element reference invokes the method <meth>[]</meth>
in the receiver, passing as parameters the expressions between
the brackets.
<p/>
When used as an lvalue, element reference invokes the method <meth>[]=</meth> in
the receiver, passing as parameters the expressions between
the brackets, followed by the <nt>rvalue</nt> being assigned.
<section>Aliasing</section>
<p/>
<syntax>
alias <nt>newName</nt> <nt>oldName</nt>
</syntax>
<p/>
creates a new name that refers to an existing method,
operator, global variable, or regular expression backreference
(<var>$&amp;</var>, <var>$'</var>, <var>$'</var>, and <var>$+</var>). Local variables,
instance variables, class variables, and constants may not be
aliased. The parameters to <tt>alias</tt> may be names or symbols.
<p/>
<codefragment>
<fullcode><![CDATA[  class Fixnum
    alias plus +
  end
  1.plus(3)

  alias $prematch $`  #!sh!
  "string" =~ /i/
  $prematch

  alias :cmd :`       #!sh!
  cmd "date"
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Fixnum</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>alias<nbsp/>plus<nbsp/>+</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>1.plus(3)</tt></td>
  <td>&#187;</td>
  <td><tt>4</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>alias<nbsp/>$prematch<nbsp/>$`</tt></td>
</tr>
<tr>
  <td><tt>"string"<nbsp/>=~<nbsp/>/i/</tt></td>
  <td>&#187;</td>
  <td><tt>3</tt></td>
</tr>
<tr>
  <td><tt>$prematch</tt></td>
  <td>&#187;</td>
  <td><tt>"str"</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>alias<nbsp/>:cmd<nbsp/>:`</tt></td>
</tr>
<tr>
  <td><tt>cmd<nbsp/>"date"</tt></td>
  <td>&#187;</td>
  <td><tt>"Sun<nbsp/>Nov<nbsp/>25<nbsp/>23:44:19<nbsp/>CST<nbsp/>2001\n"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
When a method is aliased, the new name refers to a copy of the
original method's body.
If the method is subsequently
redefined, the aliased name will still invoke the original
implementation.
<p/>
<codefragment>
<fullcode><![CDATA[    def meth
      "original method"
    end
    
    alias original meth  #!sh!
    
    def meth
      "new and improved"
    end
    meth
    original
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>meth</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"original<nbsp/>method"</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>alias<nbsp/>original<nbsp/>meth</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>def<nbsp/>meth</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"new<nbsp/>and<nbsp/>improved"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
  <td><tt>meth</tt></td>
  <td>&#187;</td>
  <td><tt>"new<nbsp/>and<nbsp/>improved"</tt></td>
</tr>
<tr>
  <td><tt>original</tt></td>
  <td>&#187;</td>
  <td><tt>"original<nbsp/>method"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Class Definition</section>
<p/>
<syntax>
class <nt>classname</nt>  <opt>&lt; <nt>superexpr</nt></opt>
  <nt>body</nt>
end
<p/>
class &lt;&lt; <nt>anObject</nt>
  <nt>body</nt>
end
</syntax>
<p/>
A Ruby class definition creates or extends an object of class
<classname>Class</classname> by executing the code in <nt>body</nt>.
In the first form, a
named class is created or extended. The resulting <classname>Class</classname> object is
assigned to a global constant named <nt>classname</nt>. This name should
start with an uppercase letter.  In the second form, an anonymous
(singleton) class is associated with the specific object.
<p/>
If present, <nt>superexpr</nt> should be an expression that evaluates to a
<classname>Class</classname> object that will be installed as the superclass of the class
being defined. If omitted, it defaults to class <classname>Object</classname>.
<p/>
Within <nt>body</nt>, most Ruby expressions are simply executed as the
definition is read. However:
<p/>
<ul>
<li> Method definitions will register the methods in a table in
  the class object.
</li><li> Nested class and module definitions will be stored in constants
  within the class, not as global constants. These nested classes and
  modules can be accessed from outside the defining class using
  ``<tt>::</tt>'' to qualify their names.  
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    module NameSpace
      class Example
        CONST = 123
      end
    end
    obj = NameSpace::Example.new
    a = NameSpace::Example::CONST
]]></fullcode>
module<nbsp/>NameSpace
<nbsp/><nbsp/>class<nbsp/>Example
<nbsp/><nbsp/><nbsp/><nbsp/>CONST<nbsp/>=<nbsp/>123
<nbsp/><nbsp/>end
end
obj<nbsp/>=<nbsp/>NameSpace::Example.new
a<nbsp/>=<nbsp/>NameSpace::Example::CONST
</alltt>
</codefragment>
<p/>
</li><li> The <cim><file>module</file><front>Module</front><back>include</back><mref>include</mref></cim> method will add the named modules as
  anonymous superclasses of the class being defined.
</li></ul>
<p/>
It is worth emphasizing that a class definition is executable code.
Many of the directives used in class definition (such as <meth>attr</meth>
and <meth>include</meth>) are actually simply private instance methods of
class <classname>Module</classname> (documented starting on page 344).
<p/>
Chapter 19, which begins
on page 237, describes in more detail how
<classname>Class</classname> objects interact with the rest of the environment.
<subsection>Creating Objects from Classes</subsection>
<syntax>
<nt>obj</nt> = <nt>classexpr</nt>.new <opt> ( <optz><nt>args</nt></optz> ) </opt>
</syntax>
<p/>
Class <classname>Class</classname> defines the instance method <cim><file>class</file><front>Class</front><back>new</back><mref>new</mref></cim>, which:
<p/>
<ul>
<li> Creates an object of the class of the receiver (<nt>classexpr</nt>
  in the syntax example).
</li><li> Sets that object's type to be the receiver.
</li><li> Invokes the instance method <meth>initialize</meth> in the newly created
  object, passing it any arguments originally passed to <meth>new</meth>.
</li></ul>
<p/>
If a class definition overrides the class method <meth>new</meth> without
calling <meth>super</meth>, no objects of that class can be created.
<subsection>Class Attribute Declarations</subsection>
<p/>
Class attribute declarations are technically not part of the Ruby
language: they are simply methods defined in class <classname>Module</classname> that
create accessor methods automatically.
<p/>
<syntax>
class <nt>name</nt>
  attr <nt>attribute</nt>  <opt>, <nt>writable</nt></opt>
  attr_reader     <optn><nt>attribute</nt></optn>
  attr_writer     <optn><nt>attribute</nt></optn>
  attr_accessor   <optn><nt>attribute</nt></optn>
end
</syntax>
<section>Module Definitions</section>
<p/>
<syntax>
module <nt>name</nt>
  <nt>body</nt>
end
</syntax>
<p/>
A module is basically a class that cannot be instantiated. Like a
class, its body is executed during definition and the resulting
<classname>Module</classname> object is stored in a constant. A module may contain
class and instance methods and may define constants and class
variables. As with classes, module methods are invoked using the
<classname>Module</classname> object as a receiver, and constants are accessed using the
``<tt>::</tt>'' scope resolution operator.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Mod
    CONST = 1
    def Mod.method1    # module method
      CONST + 1
    end
  end
]]></fullcode>
module<nbsp/>Mod
<nbsp/><nbsp/>CONST<nbsp/>=<nbsp/>1
<nbsp/><nbsp/>def<nbsp/>Mod.method1<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>module<nbsp/>method
<nbsp/><nbsp/><nbsp/><nbsp/>CONST<nbsp/>+<nbsp/>1
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
<codefragment>
<fullcode><![CDATA[!-  module Mod
!-    CONST = 1
!-    def Mod.method1    # module method
!-      CONST + 1
!-    end
!-    def method2        # instance method
!-      CONST + 2
!-    end
!-  end
  Mod::CONST
  Mod.method1
]]></fullcode><rubycode>
<tr>
  <td><tt>Mod::CONST</tt></td>
  <td>&#187;</td>
  <td><tt>1</tt></td>
</tr>
<tr>
  <td><tt>Mod.method1</tt></td>
  <td>&#187;</td>
  <td><tt>2</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Mixins---Including Modules</subsection>
<p/>
<syntax>
class|module <nt>name</nt>
  include <nt>expr</nt>
end
</syntax>
<p/>
A module may be included within the definition of another module or
class using the <meth>include</meth> method. The module or class definition
containing the <meth>include</meth> gains access to the constants, class
variables, and instance methods of the module it includes.
<p/>
If a module is included within a class definition, the module's
constants, class variables, and instance methods are effectively
bundled into an anonymous (and inaccessible) superclass for that
class. In particular, objects of the class will respond to messages
sent to the module's instance methods.
<p/>
A module may also be included at the top level, in which case the
module's constants, class variables, and instance methods become
available at the top level.
<subsubsection>Module Functions</subsubsection>
<p/>
Although <meth>include</meth> is useful for providing mixin functionality, 
it is also a way of bringing the constants, class variables, and
instance methods of a module into another namespace. However,
functionality defined in an instance method will not be available as a 
module method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Math
    def sin(x)
      #
    end
  end

  # Only way to access Math.sin is...
  include Math
  sin(1)
]]></fullcode>
module<nbsp/>Math
<nbsp/><nbsp/>def<nbsp/>sin(x)
<nbsp/><nbsp/><nbsp/><nbsp/>#
<nbsp/><nbsp/>end
end
<p/>
#<nbsp/>Only<nbsp/>way<nbsp/>to<nbsp/>access<nbsp/>Math.sin<nbsp/>is...
include<nbsp/>Math
sin(1)
</alltt>
</codefragment>
<p/>
The method <cim><file>module</file><front>Module</front><back>module_function</back><mref>module_function</mref></cim> solves this problem by taking one or 
more module instance methods and copying their definitions into
corresponding module methods.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  module Math
    def sin(x)
      #
    end
    module_function :sin
  end

  Math.sin(1)
  include Math
  sin(1)
]]></fullcode>
module<nbsp/>Math
<nbsp/><nbsp/>def<nbsp/>sin(x)
<nbsp/><nbsp/><nbsp/><nbsp/>#
<nbsp/><nbsp/>end
<nbsp/><nbsp/>module_function<nbsp/>:sin
end
<p/>
Math.sin(1)
include<nbsp/>Math
sin(1)
</alltt>
</codefragment>
<p/>
The instance method and module method are two different
methods: the method definition is copied by <meth>module_function</meth>, 
not aliased.
<section>Access Control</section>
<p/>
Ruby defines three levels of protection for module and class constants
and methods:
<p/>
<ul>
<li> <b>Public</b>. Accessible to anyone.
</li><li> <b>Protected</b>. Can be invoked only by objects of the defining
  class and its subclasses.
</li><li> <b>Private</b>. Can be called only in functional form
  (that is, with an implicit <kw>self</kw> as the receiver). Private methods 
  therefore can be called only in the defining class and by direct
  descendents within the same object.
</li></ul>
<p/>
<syntax>
private    <optz><nt>aSymbol</nt></optz>
protected  <optz><nt>aSymbol</nt></optz>
public     <optz><nt>aSymbol</nt></optz>
</syntax>
<p/>
Each function can be used in two different ways.
<ol>
<li> If used with no arguments, the three functions set the default
  access control of subsequently defined methods.
</li><li> With arguments, the functions set the access control of the
  named methods and constants.
</li></ol>
<p/>
Access control is enforced when a method is invoked.
<section>Blocks, Closures, and Proc Objects</section>
<p/>
A code block is a set of Ruby statements and expressions between braces
or a <kw>do</kw>/<kw>end</kw> pair. The block may start with an argument list
between vertical bars. A code block may appear only immediately after a 
method invocation. The start of the block must be on the same logical
line as the end of the invocation.
<p/>
<syntax>
<nt>invocation</nt>  do  | a1, a2, ... |
end
<p/>
<nt>invocation</nt>  {   | a1, a2, ... |
}
</syntax>
<p/>
Braces have a high precedence; <kw>do</kw> has a low
precedence.  If the method invocation has parameters that are not
enclosed in parentheses, the brace form of a block will bind to the
last parameter, not to the overall invocation. The <kw>do</kw> form will
bind to the invocation.
<p/>
Within the body of the invoked method, the code block may be called
using the <meth>yield</meth> method.
Parameters passed to the
<meth>yield</meth> will be assigned to arguments in the block using the
rules of parallel assignment described starting on page 219.
The return value of the <meth>yield</meth> is the value of the last
expression evaluated in the block.
<p/>
A code block remembers the environment in which it was defined, and it
uses that environment whenever it is called.
<subsection>Proc Objects</subsection>
<p/>
Code blocks are converted into objects of class <classname>Proc</classname> using the
methods <ccm><file>proc</file><front>Proc</front><back>new</back><mref>new</mref></ccm> and <mim><file>kernel</file><front>Kernel</front><back>proc</back><mref>proc</mref></mim>, or by associating the block
with a method's block argument.
<p/>
The <classname>Proc</classname> constructor takes an associated block and wraps it with
enough context to be able to re-create the block's environment when it
is subsequently called. The <cim><file>proc</file><front>Proc</front><back>call</back><mref>call</mref></cim> instance method then
allows you to invoke the original block, optionally passing in
parameters. The code in the block (and the associated closure) 
remains available for the lifetime of the <classname>Proc</classname> object.
<p/>
If the last argument in a method's argument list is prefixed with an
ampersand (``<tt>&amp;</tt>''), any block associated with calls to that method
will be converted to a <classname>Proc</classname> object and assigned to that parameter.
<section>Exceptions</section>
<p/>
Ruby exceptions are objects of class <classname>Exception</classname> and its
descendents (a full list of the built-in exceptions is given in Figure 
22.1 on page 299).
<subsection>Raising Exceptions</subsection>
<p/>
The <mmm><file>kernel</file><front>Kernel</front><back>raise</back><mref>raise</mref></mmm> method raises an exception.
<p/>
<syntax>
raise
raise <nt>aString</nt>
raise <nt>thing</nt> <opt>, <nt>aString</nt> <opt><nt>aStackTrace</nt></opt></opt>
</syntax>
<p/>
The first form reraises the exception in <var>$!</var> or a new
<classname>RuntimeError</classname> if <var>$!</var> is <tt>nil</tt>.
The second form creates a new <exception>RuntimeError</exception> exception, setting its 
message to the given string.
The third form creates an exception object by invoking the method
<meth>exception</meth> on its first argument. It then sets this
exception's message and backtrace to its second and third arguments.
Class <classname>Exception</classname> and objects of class <classname>Exception</classname> contain factory 
methods called <meth>exception</meth>, so an exception class name or
instance can be used as the first parameter to <meth>raise</meth>.
<p/>
When an exception is raised, Ruby places a reference to the
<exception>Exception</exception> object in the global variable <var>$!</var>.
<subsection>Handling Exceptions</subsection>
<p/>
Exceptions may be handled within the scope of a <kw>begin</kw>/<kw>end</kw>
block.
<p/>
<syntax>
  begin
    <nt>code...</nt>
    <nt>code...</nt>
<optz>rescue  <optz>parm</optz> <opt>=&gt; <nt>var</nt></opt> <opt>then</opt>
    <nt>error handling code...</nt> </optz>
<opt>else
    <nt>no exception code...</nt></opt>
<opt>ensure
    <nt>always executed code...</nt></opt>
  end
</syntax>
<p/>
A block may have multiple <kw>rescue</kw> clauses, and each <kw>rescue</kw>
clause may specify zero or more parameters. A <kw>rescue</kw> clause with
no parameter is treated as if it had a parameter of
<exception>StandardError</exception>.
<p/>
When an exception is raised, Ruby scans up the call stack until it
finds an enclosing <kw>begin</kw>/<kw>end</kw> block.  For each <kw>rescue</kw>
clause in that block, Ruby compares the raised exception against each
of the rescue clause's parameters in turn; each parameter is tested using
<tt>$!.kind_of?(<em>parameter</em>)</tt>.  If the raised exception matches
a <kw>rescue</kw> parameter, Ruby executes the body of the <kw>rescue</kw> and
stops looking.  If a matching <kw>rescue</kw> clause ends with <tt>=&gt;</tt> and
a variable name, the variable is set to <var>$!</var>.
<p/>
Although the parameters to the <kw>rescue</kw> clause are typically the
names of <exception>Exception</exception> classes, they can actually be arbitrary
expressions (including method calls) that return an appropriate class.
<p/>
If no rescue clause matches the raised exception, Ruby moves up the stack
frame looking for a higher-level <kw>begin</kw>/<kw>end</kw> block that
matches. If an exception propagates to the top level without being
rescued, the program terminates with a message.
<p/>
If an <kw>else</kw> clause is present,
its body is executed if no
exceptions were raised in <em>initial code</em>.
Exceptions raised during the execution of the <tt>else</tt> clause are not
captured by <tt>rescue</tt> clauses in the same block as the <tt>else</tt>.
<p/>
If an <kw>ensure</kw> clause is present,
its body is always executed
as the block is exited (even if an uncaught exception is in the
process of being propagated).
<subsubsection>Retrying a Block</subsubsection>
<p/>
The <kw>retry</kw>
statement can be used within a <kw>rescue</kw> 
clause to restart the enclosing <kw>begin</kw>/<kw>end</kw> block from the beginning.
<section>Catch and Throw</section>
<p/>
The method <mmm><file>kernel</file><front>Kernel</front><back>catch</back><mref>catch</mref></mmm> executes its associated block.
<p/>
<syntax>
catch ( <nt>aSymbol</nt> | <nt>aString</nt> )  do
  <nt>block...</nt>
end
</syntax>
<p/>
The method <mmm><file>kernel</file><front>Kernel</front><back>throw</back><mref>throw</mref></mmm> interrupts the normal processing of
statements.
<p/>
<syntax>
throw( <nt>aSymbol</nt> | <nt>aString</nt> <opt>, <nt>anObject</nt></opt> )
</syntax>
<p/>
When a <kw>throw</kw> is executed, Ruby searches up the call stack for the 
first <meth>catch</meth> block with a matching symbol or string. If it is found,
the search stops, and execution resumes past the end of the <kw>catch</kw>'s
block. If the <meth>throw</meth> was passed a second parameter, that value 
is returned as the value of the <meth>catch</meth>. Ruby honors the
<kw>ensure</kw> clauses of any block expressions it traverses while
looking for a corresponding <kw>catch</kw>.
<p/>
If no <kw>catch</kw> block matches the <kw>throw</kw>, Ruby raises a <exception>NameError</exception>
exception at the location of the <kw>throw</kw>.
</chapter>
</ppdoc>
