<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman, Inc. This material may
be distributed only subject to the terms and conditions set forth in
the Open Publication License, v1.0 or later (the latest version is
presently available at http://www.opencontent.org/openpub/).
<p/>
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
<p/>
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.
</copyright>

<chapter  ref="xref-000001" name="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>
537765312<nbsp/>537765022<nbsp/>537764992
</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/>0.410000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.410000<nbsp/>(<nbsp/><nbsp/>0.414915)
Nested:<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/><nbsp/><nbsp/>0.000000<nbsp/>(<nbsp/><nbsp/>0.001190)
</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/>
</chapter>
</ppdoc>
