<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="Ruby.new">
<p/>
When we originally wrote this book, we had a grand plan (we were
younger then). We wanted to document the language from the top down,
starting with classes and objects, and ending with the nitty-gritty
syntax details. It seemed like a good idea at the time. After all,
most everything in Ruby is an object, so it made sense to talk about
objects first.
<p/>
Or so we thought.
<p/>
Unfortunately, it turns out to be difficult to describe a language
that way. If you haven't covered strings, <tt>if</tt> statements,
assignments, and other details, it's difficult to write examples of
classes. Throughout our top-down description, we kept coming across
low-level details we needed to cover so that the example code would
make sense.
<p/>
So, we came up with another grand plan (they don't call us pragmatic
for nothing). We'd still describe Ruby starting at the top. But before
we did that, we'd add a short chapter that described all the common
language features used in the examples along with the special vocabulary
used in Ruby, a kind of minitutorial to bootstrap us into the rest of
the book.
<section>Ruby Is an Object-Oriented Language</section>
<p/>
Let's say it again. Ruby is a genuine object-oriented language.
Everything you manipulate is an object, and the results of those
manipulations are themselves objects. However, many languages make the
same claim, and they often have a different interpretation of what
object-oriented means and a different terminology for the concepts
they employ.
<p/>
So, before we get too far into the details, let's briefly look at the
terms and notation that <em>we'll</em> be using.
<p/>
When you write object-oriented code, you're normally looking to model
concepts from the real world in your code. Typically during this modeling
process you'll discover categories of things that need to be
represented in code. In a jukebox, the concept of a ``song'' might be
such a category.  In Ruby, you'd define a <em>class</em> to represent
each of these entities.  A class is a combination of state (for
example, the name of the song) and methods that use that state (perhaps
a method to play the song).
<p/>
Once you have these classes, you'll typically want to create a number
of <em>instances</em> of each. For the jukebox system containing a class
called <classname>Song</classname>, you'd have separate instances for popular hits such
as ``Ruby Tuesday,'' ``Enveloped in Python,'' ``String of Pearls,''
``Small talk,'' and so on. The word <em>object</em> is used
interchangeably with class instance (and being lazy typists, we'll
probably be using the word ``object'' more frequently).
<p/>
In Ruby, these objects are created by calling a constructor, a special
method associated with a class. The standard constructor is called
<meth>new</meth>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Song
!-def initialize(a)
!-end
!-end
  song1 = Song.new("Ruby Tuesday")
  song2 = Song.new("Enveloped in Python")
  # and so on
]]></fullcode>
song1<nbsp/>=<nbsp/>Song.new("Ruby<nbsp/>Tuesday")
song2<nbsp/>=<nbsp/>Song.new("Enveloped<nbsp/>in<nbsp/>Python")
#<nbsp/>and<nbsp/>so<nbsp/>on
</alltt>
</codefragment>
<p/>
These instances are both derived from the same class, but they have
unique characteristics.  First, every object has a unique <em>object
  identifier</em> (abbreviated as <em>object id</em>). Second, you can
define <em>instance variables</em>,
variables with values that are
unique to each instance.  These instance variables hold an object's
state.  Each of our songs, for example, will probably have an instance
variable that holds the song title.
<p/>
Within each class, you can define <em>instance methods</em>.
Each method
is a chunk of functionality which may be called from within the class
and (depending on accessibility constraints) from outside. These
instance methods in turn have access to the object's instance
variables, and hence to the object's state.
<p/>
Methods are invoked by sending a message to an object.
The message
contains the method's name, along with any parameters the method may
need.<footnote>This idea of expressing  method calls in the form of
  messages comes from Smalltalk.</footnote> When an object receives a message,
it looks into its own class for a corresponding method. If found, that 
method is executed. If the method <em>isn't</em> found, ... well,
we'll get to that later.
<p/>
This business of methods and messages may sound complicated, but in
practice it is very natural. Let's look at some method calls.
(Remember that the arrows in the code examples show the values
returned by the corresponding expressions.)
<p/>
<codefragment>
<fullcode><![CDATA[!-  someVariable = 1
!-  aSong = 1
!-  sam = ""
!-  def sam.play(a)
!-    "duh dum, da dum de dum ..."
!-  end
  "gin joint".length
  "Rick".index("c")
  -1942.abs
  sam.play(aSong)
]]></fullcode><rubycode>
<tr>
  <td><tt>"gin<nbsp/>joint".length</tt></td>
  <td>&#187;</td>
  <td><tt>9</tt></td>
</tr>
<tr>
  <td><tt>"Rick".index("c")</tt></td>
  <td>&#187;</td>
  <td><tt>2</tt></td>
</tr>
<tr>
  <td><tt>-1942.abs</tt></td>
  <td>&#187;</td>
  <td><tt>1942</tt></td>
</tr>
<tr>
  <td><tt>sam.play(aSong)</tt></td>
  <td>&#187;</td>
  <td><tt>"duh<nbsp/>dum,<nbsp/>da<nbsp/>dum<nbsp/>de<nbsp/>dum<nbsp/>..."</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Here, the thing before the period is called the <em>receiver</em>, and
the name after the period is the method to be invoked.
The first
example asks a string for its length, and the second asks a different
string to find the index of the letter ``c.'' The third line has a
number calculate its absolute value. Finally, we ask Sam to play us
a song.
<p/>
It's worth noting here a major difference between Ruby and most other
languages. In (say) Java, you'd find the absolute value of some number 
by calling a separate function and passing in that number. You might
write
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  number = Math.abs(number)     // Java code
]]></fullcode>
number<nbsp/>=<nbsp/>Math.abs(number)<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>//<nbsp/>Java<nbsp/>code
</alltt>
</codefragment>
<p/>
In Ruby, the ability to determine an absolute value is built into
numbers---they take care of the details internally. You simply send
the message <tt>abs</tt> to a number object and let it do the work.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- number = -1234
  number = number.abs
]]></fullcode>
number<nbsp/>=<nbsp/>number.abs
</alltt>
</codefragment>
<p/>
The same applies to all Ruby objects: in C you'd write
<tt>strlen(name)</tt>, while in Ruby it's <tt>name.length</tt>, and so
on. This is part of what we mean when we say that Ruby is a genuine OO 
language.
<section>Some Basic Ruby</section>
<p/>
Not many people like to read heaps of boring syntax rules when they're
picking up a new language. So we're going to cheat. In this section
we'll hit some of the highlights, the stuff you'll just <em>have</em> to
know if you're going to write Ruby programs. Later, in Chapter
18, which begins on page 199, we'll go into
all the gory details.
<p/>
Let's start off with a simple Ruby program. We'll write a method that
returns a string, adding to that string a person's
name. We'll then invoke that method a couple of times.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def sayGoodnight(name)
    result = "Goodnight, " + name
    return result
  end

  # Time for bed...
  puts sayGoodnight("John-Boy")
  puts sayGoodnight("Mary-Ellen")
]]></fullcode>
def<nbsp/>sayGoodnight(name)
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>"Goodnight,<nbsp/>"<nbsp/>+<nbsp/>name
<nbsp/><nbsp/>return<nbsp/>result
end
<p/>
#<nbsp/>Time<nbsp/>for<nbsp/>bed...
puts<nbsp/>sayGoodnight("John-Boy")
puts<nbsp/>sayGoodnight("Mary-Ellen")
</alltt>
</codefragment>
<p/>
First, some general observations. Ruby syntax is clean. You don't
need semicolons at the ends of statements as long as you put each
statement on a separate line.  Ruby comments start with a
<tt>#</tt> character and run to the end of the line. Code layout is
pretty much up to you; indentation is not significant.
<p/>
Methods are defined with the keyword <tt>def</tt>, followed by the method
name (in this case, ``<meth>sayGoodnight</meth>'') and the method's
parameters between parentheses.  Ruby doesn't use braces to delimit
the bodies of compound statements and definitions. Instead, you simply
finish the body with the keyword <tt>end</tt>.  Our method's body is
pretty simple. The first line concatenates the literal string
``Goodnight,<visible_space/>'' to the parameter <var>name</var> and assigns the result to
the local variable result. The next line returns that result to the
caller. Note that we didn't have to declare the variable <var>result</var>;
it sprang into existence when we assigned to it.
<p/>
Having defined the method, we call it twice. In both cases we pass the
result to the method <meth>puts</meth>, which simply outputs its argument
followed by a newline.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  Goodnight, John-Boy
  Goodnight, Mary-Ellen
]]></fullcode>
Goodnight,<nbsp/>John-Boy
Goodnight,<nbsp/>Mary-Ellen
</alltt>
</codefragment>
<p/>
The line ``<tt>puts sayGoodnight("John-Boy")</tt>'' contains two method calls, 
one to <meth>sayGoodnight</meth> and the other to <tt>puts</tt>. Why does one call
have its arguments in parentheses while the other doesn't? In this
case it's purely a matter of taste. The following lines are all
equivalent.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  puts sayGoodnight "John-Boy"
  puts sayGoodnight("John-Boy")
  puts(sayGoodnight "John-Boy")
  puts(sayGoodnight("John-Boy"))
]]></fullcode>
puts<nbsp/>sayGoodnight<nbsp/>"John-Boy"
puts<nbsp/>sayGoodnight("John-Boy")
puts(sayGoodnight<nbsp/>"John-Boy")
puts(sayGoodnight("John-Boy"))
</alltt>
</codefragment>
<p/>
However, life isn't always that simple, and precedence rules can make
it difficult to know which argument goes with which method invocation,
so we recommend using parentheses in all but the simplest cases.
<p/>
This example also shows some Ruby string objects. There are many ways
to create a string object, but probably the most common is to use
string literals: sequences of characters between single or double
quotation marks. The difference between the two forms is the amount of 
processing Ruby does on the string while constructing the literal. In
the single-quoted case, Ruby does very little. With a few exceptions,
what you type into the string literal becomes the string's value.
<p/>
In the double-quoted case, Ruby does more work. First, it looks for
substitutions---sequences that start with a backslash character---and
replaces them with some binary value. The most common of these is
``<tt>\n</tt>'', which is replaced with a newline character.
When a
string containing a newline is output, the ``<tt>\n</tt>'' forces a
line break.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  puts "And Goodnight,\nGrandma"
]]></fullcode>
puts<nbsp/>"And<nbsp/>Goodnight,\nGrandma"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
And<nbsp/>Goodnight,
Grandma
</alltt>
</codefragment>
<p/>
The second thing that Ruby does with double-quoted strings 
is expression interpolation. Within the string, the sequence
<tt>#{</tt><em>expression</em><tt>}</tt> is replaced by the value of
<em>expression</em>. We could use this to rewrite our previous method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def sayGoodnight(name)
    result = "Goodnight, #{name}"
    return result
  end
]]></fullcode>
def<nbsp/>sayGoodnight(name)
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>"Goodnight,<nbsp/>#{name}"
<nbsp/><nbsp/>return<nbsp/>result
end
</alltt>
</codefragment>
<p/>
When Ruby constructs this string object, it looks at the current value 
of <var>name</var> and substitutes it into the string. Arbitrarily complex 
expressions are allowed in the <tt>#{...}</tt> construct. As a
shortcut, you don't need to supply the braces when the expression is
simply a global, instance, or class variable. For more
information on strings, as well as on the other Ruby standard types, see
Chapter 5, which begins on page 47.
<p/>
Finally, we could simplify this method some more. The value returned
by a Ruby method is the value of the last expression evaluated, so we
can get rid of the <tt>return</tt> statement altogether.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def sayGoodnight(name)
    "Goodnight, #{name}"
  end
]]></fullcode>
def<nbsp/>sayGoodnight(name)
<nbsp/><nbsp/>"Goodnight,<nbsp/>#{name}"
end
</alltt>
</codefragment>
<p/>
We promised that this section would be brief. We've got just one more
topic to cover: Ruby names. For brevity, we'll be using some terms
(such as class variable) that we aren't going to
define here. However, by talking about the rules now, you'll be ahead
of the game when we actually come to discuss instance variables and
the like later.
<p/>
Ruby uses a convention to help it distinguish the usage of a name: the
first characters of a name indicate how the name is used.
Local variables, method parameters, and method names should all start
with a lowercase letter or with an underscore. Global variables are
prefixed with a dollar sign ($), while instance variables begin with
an ``at'' sign (@). Class variables start with two ``at'' signs (@@). Finally,
class names, module names, and constants should
start with an uppercase letter. Samples of different names are given
in Table 2.1 on page 10.
<p/>
Following this initial character, a name can be any combination of
letters, digits, and underscores (with the proviso that the character
following an @ sign may not be a digit).
<p/>
<figure type="table">
  <caption>Example variable and class names</caption>
<center>
    <table>
<th>
<td colspan="4"><b>Variables</b></td>
  <td><b>Constants and</b></td>
</th>
<th>
  <td><b>Local</b></td>
  <td><b>Global</b></td>
  <td><b>Instance</b></td>
  <td><b>Class</b></td>
  <td><b>Class Names</b></td>
</th>
<tr>
  <td><tt>name</tt></td>
  <td><tt>$debug</tt></td>
  <td><tt>@name</tt></td>
  <td><tt>@@total</tt></td>
  <td><tt>PI</tt></td>
</tr>
<tr>
  <td><tt>fishAndChips</tt></td>
  <td><tt>$CUSTOMER</tt></td>
  <td><tt>@point_1</tt></td>
  <td><tt>@@symtab</tt></td>
  <td><tt>FeetPerMile</tt></td>
</tr>
<tr>
  <td><tt>x_axis</tt></td>
  <td><tt>$_</tt></td>
  <td><tt>@X</tt></td>
  <td><tt>@@N</tt></td>
  <td><tt>String</tt></td>
</tr>
<tr>
  <td><tt>thx1138</tt></td>
  <td><tt>$plan9</tt></td>
  <td><tt>@_</tt></td>
  <td><tt>@@x_pos</tt></td>
  <td><tt>MyClass</tt></td>
</tr>
<tr>
  <td><tt>_26</tt></td>
  <td><tt>$Global</tt></td>
  <td><tt>@plan9</tt></td>
  <td><tt>@@SINGLE</tt></td>
  <td><tt>Jazz_Song</tt></td>
</tr>
<bottomrule/></table>
<p/>
</center>
</figure>
<p/>
<section>Arrays and Hashes</section>
<p/>
Ruby's arrays and hashes are indexed collections. Both store
collections of objects, accessible using a key. With arrays, the key
is an integer, whereas hashes support any object as a key.  Both
arrays and hashes grow as needed to hold new elements.  It's more
efficient to access array elements, but hashes provide more
flexibility. Any particular array or hash can hold objects of
differing types; you can have an array containing an integer, a
string, and a floating point number, as we'll see in a minute.
<p/>
You can create and initialize a new array using an array literal---a
set of elements between square brackets. Given an array object, you
can access individual elements by supplying an index between
square brackets, as the next example shows.
<p/>
<codefragment>
<fullcode><![CDATA[  a = [ 1, 'cat', 3.14 ]   # array with three elements
  # access the first element
  a[0]
  # set the third element
  a[2] = nil
  # dump out the array
  a
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>'cat',<nbsp/>3.14<nbsp/>]<nbsp/><nbsp/><nbsp/>#<nbsp/>array<nbsp/>with<nbsp/>three<nbsp/>elements</tt></td>
</tr>
<tr>
<td colspan="3"><tt>#<nbsp/>access<nbsp/>the<nbsp/>first<nbsp/>element</tt></td>
</tr>
<tr>
  <td><tt>a[0]</tt></td>
  <td>&#187;</td>
  <td><tt>1</tt></td>
</tr>
<tr>
<td colspan="3"><tt>#<nbsp/>set<nbsp/>the<nbsp/>third<nbsp/>element</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a[2]<nbsp/>=<nbsp/>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt>#<nbsp/>dump<nbsp/>out<nbsp/>the<nbsp/>array</tt></td>
</tr>
<tr>
  <td><tt>a</tt></td>
  <td>&#187;</td>
  <td><tt>[1,<nbsp/>"cat",<nbsp/>nil]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can create empty arrays either by using an array literal with no
elements or by using the array object's constructor, <ccm><file>array</file><front>Array</front><back>new</back><mref>new</mref></ccm>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  empty1 = []
  empty2 = Array.new
]]></fullcode>
empty1<nbsp/>=<nbsp/>[]
empty2<nbsp/>=<nbsp/>Array.new
</alltt>
</codefragment>
<p/>
Sometimes creating arrays of words can be a pain, what with all the
quotes and commas. Fortunately, there's a shortcut: <tt>%w</tt> does just 
what we want.
<p/>
<codefragment>
<fullcode><![CDATA[  a = %w{ ant bee cat dog elk }
  a[0]
  a[3]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>%w{<nbsp/>ant<nbsp/>bee<nbsp/>cat<nbsp/>dog<nbsp/>elk<nbsp/>}</tt></td>
</tr>
<tr>
  <td><tt>a[0]</tt></td>
  <td>&#187;</td>
  <td><tt>"ant"</tt></td>
</tr>
<tr>
  <td><tt>a[3]</tt></td>
  <td>&#187;</td>
  <td><tt>"dog"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Ruby hashes are similar to arrays. A hash literal uses braces rather than
square brackets. The literal must supply two objects for every
entry: one for the key, the other for the value.
<p/>
For example, you might want to map musical instruments to their
orchestral sections. You could do this with a hash.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  instSection = {
    'cello'     => 'string',
    'clarinet'  => 'woodwind',
    'drum'      => 'percussion',
    'oboe'      => 'woodwind',
    'trumpet'   => 'brass',
    'violin'    => 'string'
  }
]]></fullcode>
instSection<nbsp/>=<nbsp/>{
<nbsp/><nbsp/>'cello'<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>'string',
<nbsp/><nbsp/>'clarinet'<nbsp/><nbsp/>=&gt;<nbsp/>'woodwind',
<nbsp/><nbsp/>'drum'<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>'percussion',
<nbsp/><nbsp/>'oboe'<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>'woodwind',
<nbsp/><nbsp/>'trumpet'<nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>'brass',
<nbsp/><nbsp/>'violin'<nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>'string'
}
</alltt>
</codefragment>
<p/>
Hashes are indexed using the same square bracket notation as arrays.
<p/>
<codefragment>
<fullcode><![CDATA[!-  instSection = {
!-    'cello'     => 'string',
!-    'clarinet'  => 'woodwind',
!-    'drum'      => 'percussion',
!-    'oboe'      => 'woodwind',
!-    'trumpet'   => 'brass',
!-    'violin'    => 'string'
!-  }
  instSection['oboe']
  instSection['cello']
  instSection['bassoon']
]]></fullcode><rubycode>
<tr>
  <td><tt>instSection['oboe']</tt></td>
  <td>&#187;</td>
  <td><tt>"woodwind"</tt></td>
</tr>
<tr>
  <td><tt>instSection['cello']</tt></td>
  <td>&#187;</td>
  <td><tt>"string"</tt></td>
</tr>
<tr>
  <td><tt>instSection['bassoon']</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
As the last example shows, a hash by default returns <tt>nil</tt> when
indexed by a key it doesn't contain. Normally this is convenient, as
<tt>nil</tt> means <const>false</const> when used in conditional expressions.
Sometimes you'll want to change this default. For example, if you're
using a hash to count the number of times each key occurs, it's
convenient to have the default value be zero. This is easily done by
specifying a default value when you create a new, empty
hash.
<p/>
<codefragment>
<fullcode><![CDATA[  histogram = Hash.new(0)
  histogram['key1']
  histogram['key1'] = histogram['key1'] + 1
  histogram['key1']
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>histogram<nbsp/>=<nbsp/>Hash.new(0)</tt></td>
</tr>
<tr>
  <td><tt>histogram['key1']</tt></td>
  <td>&#187;</td>
  <td><tt>0</tt></td>
</tr>
<tr>
<td colspan="3"><tt>histogram['key1']<nbsp/>=<nbsp/>histogram['key1']<nbsp/>+<nbsp/>1</tt></td>
</tr>
<tr>
  <td><tt>histogram['key1']</tt></td>
  <td>&#187;</td>
  <td><tt>1</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Array and hash objects have lots of useful methods: see the discussion
starting on page 33, and the reference sections starting on
pages 278 and 317, for details.
<section>Control Structures</section>
<p/>
Ruby has all the usual control structures, such as <tt>if</tt> statements
and <tt>while</tt> loops. Java, C, and Perl programmers may well get
caught by the lack of braces around the bodies of these
statements. Instead, Ruby uses the keyword <tt>end</tt> to signify the end 
of a body.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- count = 99
  if count > 10
    puts "Try again"
  elsif tries == 3
    puts "You lose"
  else
    puts "Enter a number"
  end
]]></fullcode>
if<nbsp/>count<nbsp/>&gt;<nbsp/>10
<nbsp/><nbsp/>puts<nbsp/>"Try<nbsp/>again"
elsif<nbsp/>tries<nbsp/>==<nbsp/>3
<nbsp/><nbsp/>puts<nbsp/>"You<nbsp/>lose"
else
<nbsp/><nbsp/>puts<nbsp/>"Enter<nbsp/>a<nbsp/>number"
end
</alltt>
</codefragment>
<p/>
Similarly, <tt>while</tt> statements are terminated with <tt>end</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-numPallets = 101
!-weight = 1
  while weight < 100 and numPallets <= 30
    pallet = nextPallet()
    weight += pallet.weight
    numPallets += 1
  end
]]></fullcode>
while<nbsp/>weight<nbsp/>&lt;<nbsp/>100<nbsp/>and<nbsp/>numPallets<nbsp/>&lt;=<nbsp/>30
<nbsp/><nbsp/>pallet<nbsp/>=<nbsp/>nextPallet()
<nbsp/><nbsp/>weight<nbsp/>+=<nbsp/>pallet.weight
<nbsp/><nbsp/>numPallets<nbsp/>+=<nbsp/>1
end
</alltt>
</codefragment>
<p/>
Ruby <em>statement modifiers</em> are a useful shortcut if the body of an
<tt>if</tt> or <tt>while</tt> statement is just a single expression. Simply
write the expression, followed by <tt>if</tt> or <tt>while</tt> and the
condition.
For example, here's a simple <tt>if</tt> statement.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- radiation = 1
  if radiation > 3000
    puts "Danger, Will Robinson"
  end
]]></fullcode>
if<nbsp/>radiation<nbsp/>&gt;<nbsp/>3000
<nbsp/><nbsp/>puts<nbsp/>"Danger,<nbsp/>Will<nbsp/>Robinson"
end
</alltt>
</codefragment>
<p/>
Here it is again, rewritten using a statement modifier.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- radiation = 1
  puts "Danger, Will Robinson" if radiation > 3000
]]></fullcode>
puts<nbsp/>"Danger,<nbsp/>Will<nbsp/>Robinson"<nbsp/>if<nbsp/>radiation<nbsp/>&gt;<nbsp/>3000
</alltt>
</codefragment>
<p/>
Similarly, a <tt>while</tt> loop such as 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-square = 9999
  while square < 1000
     square = square*square
  end
]]></fullcode>
while<nbsp/>square<nbsp/>&lt;<nbsp/>1000
<nbsp/><nbsp/><nbsp/>square<nbsp/>=<nbsp/>square*square
end
</alltt>
</codefragment>
<p/>
becomes the more concise
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-square = 9999
  square = square*square  while square < 1000
]]></fullcode>
square<nbsp/>=<nbsp/>square*square<nbsp/><nbsp/>while<nbsp/>square<nbsp/>&lt;<nbsp/>1000
</alltt>
</codefragment>
<p/>
These statement modifiers should seem familiar to Perl programmers.
<section>Regular Expressions</section>
<p/>
Most of Ruby's built-in types will be familiar to all programmers.  A
majority of languages have strings, integers, floats, arrays, and so
on.  However, until Ruby came along, regular expression support was
generally  built into only the so-called scripting languages, such as
Perl, Python, and awk. This is a shame: regular expressions, although
cryptic, are a powerful tool for working with text.
<p/>
Entire books have been written about regular expressions (for example,
<em>Mastering Regular Expressions</em><nbsp/>), so we
won't try to cover everything in just a short section. Instead, we'll
look at just a few examples of regular expressions in action. You'll
find full coverage of regular expressions starting
on page 56.
<p/>
A regular expression is simply a way of specifying a <em>pattern</em> of
characters to be matched in a string. In Ruby, you typically create a
regular expression by writing a pattern between slash characters
(/<em>pattern</em>/).  And, Ruby being Ruby, regular expressions are of
course objects and can be manipulated as such.
<p/>
For example, you could write a pattern that matches a string
containing the text ``Perl'' or the text ``Python'' using the
following regular expression.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  /Perl|Python/
]]></fullcode>
/Perl|Python/
</alltt>
</codefragment>
<p/>
The forward slashes delimit the pattern, which consists of the two
things we're matching, separated by a pipe character (``<tt>|</tt>'').
You can use parentheses within patterns, just as you can in arithmetic 
expressions, so you could also have written this pattern as
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  /P(erl|ython)/
]]></fullcode>
/P(erl|ython)/
</alltt>
</codefragment>
<p/>
You can also specify repetition within patterns. <tt>/ab+c/</tt> matches a 
string containing an ``a'' followed by one or more ``b''s, followed by 
a ``c''. Change the plus to an asterisk, and <tt>/ab*c/</tt> creates a
regular expression that matches an ``a'', zero or more ``b''s, and a
``c''.
<p/>
You can also match one of a group of characters within a pattern. Some
common examples are character classes such as ``<tt>\s</tt>'', which
matches a whitespace character (space, tab, newline, and so on),
``<tt>\d</tt>'', which matches any digit, and ``<tt>\w</tt>'', which matches
any character that may appear in a typical word. The single character
``.'' (a period) matches any character.
<p/>
We can put all this together to produce some useful regular
expressions.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  /\d\d:\d\d:\d\d/     # a time such as 12:34:56
  /Perl.*Python/       # Perl, zero or more other chars, then Python
  /Perl\s+Python/      # Perl, one or more spaces, then Python
  /Ruby (Perl|Python)/ # Ruby, a space, and either Perl or Python
]]></fullcode>
/\d\d:\d\d:\d\d/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>a<nbsp/>time<nbsp/>such<nbsp/>as<nbsp/>12:34:56
/Perl.*Python/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Perl,<nbsp/>zero<nbsp/>or<nbsp/>more<nbsp/>other<nbsp/>chars,<nbsp/>then<nbsp/>Python
/Perl\s+Python/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Perl,<nbsp/>one<nbsp/>or<nbsp/>more<nbsp/>spaces,<nbsp/>then<nbsp/>Python
/Ruby<nbsp/>(Perl|Python)/<nbsp/>#<nbsp/>Ruby,<nbsp/>a<nbsp/>space,<nbsp/>and<nbsp/>either<nbsp/>Perl<nbsp/>or<nbsp/>Python
</alltt>
</codefragment>
<p/>
Once you have created a pattern, it seems a shame not to use it. The
match operator ``<tt>=~</tt>'' can be used to match a string against a
regular expression. If the pattern is found in the string, <tt>=~</tt>
returns its starting position, otherwise it returns <tt>nil</tt>. This means
you can use regular expressions as the condition in <tt>if</tt> and
<tt>while</tt> statements. For example, the following code fragment writes
a message if a string contains the text 'Perl' or 'Python'.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- line = "abc"
  if line =~ /Perl|Python/
    puts "Scripting language mentioned: #{line}"
  end
]]></fullcode>
if<nbsp/>line<nbsp/>=~<nbsp/>/Perl|Python/
<nbsp/><nbsp/>puts<nbsp/>"Scripting<nbsp/>language<nbsp/>mentioned:<nbsp/>#{line}"
end
</alltt>
</codefragment>
<p/>
The part of a string matched by a regular expression can also be
replaced with different text using one of Ruby's substitution methods.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- line = "abc"
  line.sub(/Perl/, 'Ruby')    # replace first 'Perl' with 'Ruby'
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'
]]></fullcode>
line.sub(/Perl/,<nbsp/>'Ruby')<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>replace<nbsp/>first<nbsp/>'Perl'<nbsp/>with<nbsp/>'Ruby'
line.gsub(/Python/,<nbsp/>'Ruby')<nbsp/>#<nbsp/>replace<nbsp/>every<nbsp/>'Python'<nbsp/>with<nbsp/>'Ruby'
</alltt>
</codefragment>
<p/>
We'll have a lot more to say about regular expressions as we go
through the book.
<section>Blocks and Iterators</section>
<p/>
This section briefly describes one of Ruby's particular strengths.  We're
about to look at code blocks: chunks of code that you can associate
with method invocations, almost as if they were parameters. This is an
incredibly powerful feature. You can use code blocks to implement
callbacks (but they're simpler than Java's anonymous inner classes),
to pass around chunks of code (but they're more flexible than C's
function pointers), and to implement iterators.
<p/>
Code blocks are just chunks of code between braces or
<tt>do</tt>...<tt>end</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  { puts "Hello" }       # this is a block

  do                     #
    club.enroll(person)  # and so is this
    person.socialize     #
  end                    #
]]></fullcode>
{<nbsp/>puts<nbsp/>"Hello"<nbsp/>}<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>this<nbsp/>is<nbsp/>a<nbsp/>block
<p/>
do<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#
<nbsp/><nbsp/>club.enroll(person)<nbsp/><nbsp/>#<nbsp/>and<nbsp/>so<nbsp/>is<nbsp/>this
<nbsp/><nbsp/>person.socialize<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#
end<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#
</alltt>
</codefragment>
<p/>
Once you've created a block, you can associate it with a call to a
method. That method can then invoke the block one or more times
using the Ruby <tt>yield</tt> statement.  The following example shows this
in action. We define a method that calls <tt>yield</tt> twice. We then
call it, putting a block on the same line, after the call (and after
any arguments to the method).<footnote>Some people like to think of
  the association of a block with a method as a kind of parameter
  passing. This works on one level, but it isn't really the whole
  story. You might be better off thinking of the block and the method
  as coroutines, which
  transfer control back and forth between themselves.</footnote>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def callBlock
    yield
    yield
  end

  callBlock { puts "In the block" }
]]></fullcode>
def<nbsp/>callBlock
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>yield
end
<p/>
callBlock<nbsp/>{<nbsp/>puts<nbsp/>"In<nbsp/>the<nbsp/>block"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
In<nbsp/>the<nbsp/>block
In<nbsp/>the<nbsp/>block
</alltt>
</codefragment>
<p/>
See how the code in the block (<tt>puts "In the block"</tt>) is executed
twice, once for each call to <tt>yield</tt>.
<p/>
You can provide parameters to the call to
<tt>yield</tt>: these will be passed to the block. Within the block, you
list the names of the arguments to receive these parameters between
vertical bars (``|'').
<p/>
<codefragment>
<alltt>
  def callBlock
    yield , 
  end
<p/>
  callBlock { |, | ... }
</alltt>
</codefragment>
<p/>
Code blocks are used throughout the Ruby library to implement
iterators: methods that return successive elements from some kind of
collection, such as an array. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  a = %w( ant bee cat dog elk )    # create an array
  a.each { |animal| puts animal }  # iterate over the contents
]]></fullcode>
a<nbsp/>=<nbsp/>%w(<nbsp/>ant<nbsp/>bee<nbsp/>cat<nbsp/>dog<nbsp/>elk<nbsp/>)<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>create<nbsp/>an<nbsp/>array
a.each<nbsp/>{<nbsp/>|animal|<nbsp/>puts<nbsp/>animal<nbsp/>}<nbsp/><nbsp/>#<nbsp/>iterate<nbsp/>over<nbsp/>the<nbsp/>contents
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
ant
bee
cat
dog
elk
</alltt>
</codefragment>
<p/>
Let's look at how we might implement the <classname>Array</classname> class's <tt>each</tt>
iterator that we used in the previous example.  The <meth>each</meth>
iterator loops through every element in the array,
calling <tt>yield</tt> for each one. In pseudo code, this might look like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  # within class Array...
  def each
    for each element
      yield(element)
    end
  end
]]></fullcode>
#<nbsp/>within<nbsp/>class<nbsp/>Array...
def<nbsp/>each
<nbsp/><nbsp/>for<nbsp/>each<nbsp/>element
<nbsp/><nbsp/><nbsp/><nbsp/>yield(element)
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
You could then iterate over an array's elements by calling its
<tt>each</tt> method and supplying a block. This block would be called for
each element in turn.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  [ 'cat', 'dog', 'horse' ].each do |animal|
    print animal, " -- "
  end
!- print "\n"
]]></fullcode>
[<nbsp/>'cat',<nbsp/>'dog',<nbsp/>'horse'<nbsp/>].each<nbsp/>do<nbsp/>|animal|
<nbsp/><nbsp/>print<nbsp/>animal,<nbsp/>"<nbsp/>--<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
cat<nbsp/>--<nbsp/>dog<nbsp/>--<nbsp/>horse<nbsp/>--
</alltt>
</codefragment>
<p/>
Similarly, many looping constructs that are built into languages such 
as C and Java are simply method calls in Ruby, with the methods
invoking the associated block zero or more times.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  5.times {  print "*" }
  3.upto(6) {|i|  print i }
  ('a'..'e').each {|char| print char }
!- puts
]]></fullcode>
5.times<nbsp/>{<nbsp/><nbsp/>print<nbsp/>"*"<nbsp/>}
3.upto(6)<nbsp/>{|i|<nbsp/><nbsp/>print<nbsp/>i<nbsp/>}
('a'..'e').each<nbsp/>{|char|<nbsp/>print<nbsp/>char<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
*****3456abcde
</alltt>
</codefragment>
<p/>
Here we ask the number 5 to call a block five times, then ask
the number 3 to call a block, passing in successive values until
it reaches 6. Finally, the range of characters from ``a'' to ``e''
invokes a block using the method <meth>each</meth>.
<section>Reading and 'Riting</section>
<p/>
Ruby comes with a comprehensive I/O library. However, in most of the
examples in this book we'll stick to a few simple methods. We've
already come across two methods that do output. <tt>puts</tt> writes each
of its arguments, adding a newline after each. <tt>print</tt> also writes
its arguments, but with no newline. Both can be used to write to any
I/O object, but by default they write to the console.
<p/>
Another output method we use a lot is <meth>printf</meth>, which prints
its arguments under the control of a format string (just like
<tt>printf</tt> in C or Perl).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  printf "Number: %5.2f, String: %s", 1.23, "hello"
]]></fullcode>
printf<nbsp/>"Number:<nbsp/>%5.2f,<nbsp/>String:<nbsp/>%s",<nbsp/>1.23,<nbsp/>"hello"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Number:<nbsp/><nbsp/>1.23,<nbsp/>String:<nbsp/>hello
</alltt>
</codefragment>
<p/>
In this example, the format string <tt>"Number: %5.2f, String: %s"</tt>
tells <meth>printf</meth> to substitute in a floating point number
(allowing five characters in total, with two after the decimal point)
and a string.
<p/>
There are many ways to read input into your program. Probably the most 
traditional is to use the routine <tt>gets</tt>, which returns the next
line from your program's standard input stream.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  line = gets
  print line
]]></fullcode>
line<nbsp/>=<nbsp/>gets
print<nbsp/>line
</alltt>
</codefragment>
<p/>
The <tt>gets</tt> routine has a side effect: as well as returning the line 
just read, it also stores it into the global variable
<var>$_</var>. This variable is special, in that it is used as the
default argument in many circumstances. If you call <tt>print</tt> with no
argument, it prints the contents of <var>$_</var>. If you write an <tt>if</tt> 
or <tt>while</tt> statement with just a regular expression as the
condition, that expression is matched against <var>$_</var>. While viewed
by some purists as a rebarbative barbarism, these abbreviations can
help you write some concise programs. For example, the following
program prints all lines in the input stream that contain the word
``Ruby.''
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  while gets           # assigns line to $_
    if /Ruby/          # matches against $_
      print            # prints $_
    end
  end
]]></fullcode>
while<nbsp/>gets<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>assigns<nbsp/>line<nbsp/>to<nbsp/>$_
<nbsp/><nbsp/>if<nbsp/>/Ruby/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>matches<nbsp/>against<nbsp/>$_
<nbsp/><nbsp/><nbsp/><nbsp/>print<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>prints<nbsp/>$_
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The ``Ruby way'' to write this would be to use an iterator.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  ARGF.each { |line|  print line  if line =~ /Ruby/ }
]]></fullcode>
ARGF.each<nbsp/>{<nbsp/>|line|<nbsp/><nbsp/>print<nbsp/>line<nbsp/><nbsp/>if<nbsp/>line<nbsp/>=~<nbsp/>/Ruby/<nbsp/>}
</alltt>
</codefragment>
<p/>
This uses the predefined object <var>ARGF</var>, which represents the
input stream that can be read by a program.
<section>Onward and Upward</section>
<p/>
That's it. We've finished our lightning-fast tour of some of the
basic features of Ruby.  We've had a brief look at objects, methods,
strings, containers, and regular expressions, seen some simple control
structures, and looked at some rather nifty iterators. Hopefully, this
chapter has given you enough ammunition to be able to attack the rest
of this book.
<p/>
Time to move on, and up---up to a higher level. Next, we'll be looking
at classes and objects, things that are at the same time both the 
highest-level constructs in Ruby and the essential underpinnings of
the entire language.
</chapter>
</ppdoc>
