<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="More About Methods">
<p/>
Other languages have functions, procedures, methods, or routines, but
in Ruby there is only the <em>method</em>---a chunk of expressions that
return a value.
<p/>
So far in this book, we've been defining and using methods without
much thought. Now it's time to get into the details.
<section>Defining a Method</section>
<p/>
As we've seen throughout this book, a method is defined using the
keyword <kw>def</kw>.
Method names should begin with a lowercase
letter.<footnote>You won't get an immediate error if you use an
  uppercase letter, but when Ruby sees you calling the method, it
  will first guess that it is a constant, not a method invocation, and
  as a result it may parse the call incorrectly.</footnote>  Methods that act as
queries are often named with a trailing ``<tt>?</tt>'', such as
<tt>instance_of?</tt>.  Methods that are ``dangerous,'' or modify the
receiver, might be named with a trailing ``<tt>!</tt>''.  For instance,
<tt>String</tt> provides both a <tt>chop</tt> and a <tt>chop!</tt>.  The first one
returns a modified string; the second modifies the receiver in
place. ``<tt>?</tt>'' and ``<tt>!</tt>'' are the only weird characters allowed 
as method name suffixes.
<p/>
Now that we've specified a name for our new method, we may need to
declare some parameters.
These are simply a list of local variable
names in parentheses.  Some sample method declarations are
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def myNewMethod(arg1, arg2, arg3)     # 3 arguments
    # Code for the method would go here
  end

  def myOtherNewMethod                  # No arguments
    # Code for the method would go here
  end
]]></fullcode>
def<nbsp/>myNewMethod(arg1,<nbsp/>arg2,<nbsp/>arg3)<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>3<nbsp/>arguments
<nbsp/><nbsp/>#<nbsp/>Code<nbsp/>for<nbsp/>the<nbsp/>method<nbsp/>would<nbsp/>go<nbsp/>here
end
<p/>
def<nbsp/>myOtherNewMethod<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>No<nbsp/>arguments
<nbsp/><nbsp/>#<nbsp/>Code<nbsp/>for<nbsp/>the<nbsp/>method<nbsp/>would<nbsp/>go<nbsp/>here
end
</alltt>
</codefragment>
<p/>
Ruby lets you specify default values for a method's arguments---values
that will be used if the caller doesn't pass them explicitly. This is
done using the assignment operator.
<p/>
<codefragment>
<fullcode><![CDATA[  def coolDude(arg1="Miles", arg2="Coltrane", arg3="Roach")
    "#{arg1}, #{arg2}, #{arg3}."
  end

  coolDude
  coolDude("Bart")
  coolDude("Bart", "Elwood")
  coolDude("Bart", "Elwood", "Linus")
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>coolDude(arg1="Miles",<nbsp/>arg2="Coltrane",<nbsp/>arg3="Roach")</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"#{arg1},<nbsp/>#{arg2},<nbsp/>#{arg3}."</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>coolDude</tt></td>
  <td>&#187;</td>
  <td><tt>"Miles,<nbsp/>Coltrane,<nbsp/>Roach."</tt></td>
</tr>
<tr>
  <td><tt>coolDude("Bart")</tt></td>
  <td>&#187;</td>
  <td><tt>"Bart,<nbsp/>Coltrane,<nbsp/>Roach."</tt></td>
</tr>
<tr>
  <td><tt>coolDude("Bart",<nbsp/>"Elwood")</tt></td>
  <td>&#187;</td>
  <td><tt>"Bart,<nbsp/>Elwood,<nbsp/>Roach."</tt></td>
</tr>
<tr>
  <td><tt>coolDude("Bart",<nbsp/>"Elwood",<nbsp/>"Linus")</tt></td>
  <td>&#187;</td>
  <td><tt>"Bart,<nbsp/>Elwood,<nbsp/>Linus."</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The body of a method contains normal Ruby expressions, except that you may
not define an instance method, class, or module within a method.  The
return value of a method is the value of the last expression executed,
or the result of an explicit <kw>return</kw> expression.
<subsection>Variable-Length Argument Lists</subsection>
<p/>
But what if you want to pass in a variable number of arguments, or
want to capture multiple arguments into a single parameter?
Placing an asterisk before the name of the parameter after the
``normal'' parameters does just that.
<p/>
<codefragment>
<fullcode><![CDATA[  def varargs(arg1, *rest)
    "Got #{arg1} and #{rest.join(', ')}"
  end

  varargs("one")
  varargs("one", "two")
  varargs "one", "two", "three"
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>varargs(arg1,<nbsp/>*rest)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"Got<nbsp/>#{arg1}<nbsp/>and<nbsp/>#{rest.join(',<nbsp/>')}"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>varargs("one")</tt></td>
  <td>&#187;</td>
  <td><tt>"Got<nbsp/>one<nbsp/>and<nbsp/>"</tt></td>
</tr>
<tr>
  <td><tt>varargs("one",<nbsp/>"two")</tt></td>
  <td>&#187;</td>
  <td><tt>"Got<nbsp/>one<nbsp/>and<nbsp/>two"</tt></td>
</tr>
<tr>
  <td><tt>varargs<nbsp/>"one",<nbsp/>"two",<nbsp/>"three"</tt></td>
  <td>&#187;</td>
  <td><tt>"Got<nbsp/>one<nbsp/>and<nbsp/>two,<nbsp/>three"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
In this example, the first argument is assigned to the first method
parameter as usual. However, the next parameter is prefixed with an
asterisk, so all the remaining arguments are bundled into a new
<classname>Array</classname>, which is then assigned to that parameter.
<subsection>Methods and Blocks</subsection>
<p/>
As we discussed in the section on blocks and iterators beginning
on page 38, when a method is called, it may be
associated with a block. Normally, you simply call the block from
within the method using
<kw>yield</kw>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  def takeBlock(p1)
    if block_given?
      yield(p1)
    else
      p1
    end
  end
]]></fullcode>
def<nbsp/>takeBlock(p1)
<nbsp/><nbsp/>if<nbsp/>block_given?
<nbsp/><nbsp/><nbsp/><nbsp/>yield(p1)
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>p1
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
<codefragment>
<fullcode><![CDATA[!-  def takeBlock(p1)
!-    if block_given?
!-      yield(p1)
!-    else
!-      p1
!-    end
!-  end
  takeBlock("no block")
  takeBlock("no block") { |s| s.sub(/no /, '') }
]]></fullcode><rubycode>
<tr>
  <td><tt>takeBlock("no<nbsp/>block")</tt></td>
  <td>&#187;</td>
  <td><tt>"no<nbsp/>block"</tt></td>
</tr>
<tr>
  <td><tt>takeBlock("no<nbsp/>block")<nbsp/>{<nbsp/>|s|<nbsp/>s.sub(/no<nbsp/>/,<nbsp/>'')<nbsp/>}</tt></td>
  <td>&#187;</td>
  <td><tt>"block"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
However, if the last parameter in a method definition is
prefixed with an ampersand, any associated block is converted to a
<classname>Proc</classname> object, and that object is assigned to the parameter.
<p/>
<codefragment>
<fullcode><![CDATA[  class TaxCalculator
    def initialize(name, &block)
      @name, @block = name, block
    end
    def getTax(amount)
      "#@name on #{amount} = #{ @block.call(amount) }"
    end
  end

  tc = TaxCalculator.new("Sales tax") { |amt| amt * 0.075 }

  tc.getTax(100)
  tc.getTax(250)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>TaxCalculator</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>initialize(name,<nbsp/>&amp;block)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@name,<nbsp/>@block<nbsp/>=<nbsp/>name,<nbsp/>block</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>getTax(amount)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"#@name<nbsp/>on<nbsp/>#{amount}<nbsp/>=<nbsp/>#{<nbsp/>@block.call(amount)<nbsp/>}"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>tc<nbsp/>=<nbsp/>TaxCalculator.new("Sales<nbsp/>tax")<nbsp/>{<nbsp/>|amt|<nbsp/>amt<nbsp/>*<nbsp/>0.075<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>tc.getTax(100)</tt></td>
  <td>&#187;</td>
  <td><tt>"Sales<nbsp/>tax<nbsp/>on<nbsp/>100<nbsp/>=<nbsp/>7.5"</tt></td>
</tr>
<tr>
  <td><tt>tc.getTax(250)</tt></td>
  <td>&#187;</td>
  <td><tt>"Sales<nbsp/>tax<nbsp/>on<nbsp/>250<nbsp/>=<nbsp/>18.75"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Calling a Method</section>
<p/>
You call a method by specifying a receiver, the name of the method,
and optionally some parameters and an associated block.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    class T
!-      def downloadMP3(name)
!-      end
!-    end
!-  connection = T.new
  connection.downloadMP3("jitterbug") { |p| showProgress(p) }
]]></fullcode>
connection.downloadMP3("jitterbug")<nbsp/>{<nbsp/>|p|<nbsp/>showProgress(p)<nbsp/>}
</alltt>
</codefragment>
<p/>
In this example, the object <tt>connection</tt> is the receiver,
<meth>downloadMP3</meth> is the name of the method, <tt>"jitterbug"</tt> is
the parameter, and the stuff between the braces is the associated
block.
<p/>
For class and module methods, the receiver will be the class or module
name.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  File.size("testfile")
  Math.sin(Math::PI/4)
]]></fullcode>
File.size("testfile")
Math.sin(Math::PI/4)
</alltt>
</codefragment>
<p/>
If you omit the receiver, it defaults to <var>self</var>, the current
object.
<p/>
<codefragment>
<fullcode><![CDATA[  self.id
  id
  self.type
  type
]]></fullcode><rubycode>
<tr>
  <td><tt>self.id</tt></td>
  <td>&#187;</td>
  <td><tt>537790064</tt></td>
</tr>
<tr>
  <td><tt>id</tt></td>
  <td>&#187;</td>
  <td><tt>537790064</tt></td>
</tr>
<tr>
  <td><tt>self.type</tt></td>
  <td>&#187;</td>
  <td><tt>Object</tt></td>
</tr>
<tr>
  <td><tt>type</tt></td>
  <td>&#187;</td>
  <td><tt>Object</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This defaulting mechanism is how Ruby implements private
methods. Private methods may <em>not</em> be called with a receiver, so
they must be methods available in the current object.
<p/>
The optional parameters follow the method name.  If there is no
ambiguity you can omit the parentheses around the argument list when
calling a method.<footnote>Other Ruby documentation sometimes calls
  these method calls without parentheses ``commands.''</footnote>  However,
except in the simplest cases we don't recommend this---there are some
subtle problems that can trip you up.<footnote>In particular, you
  <em>must</em> use parentheses on a method call that is itself a
  parameter to another method call (unless it is the last parameter).</footnote>
Our rule is simple: if there's any doubt, use parentheses.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class S
!-    def someMethod(a,b,c)
!-    end
!-  end
!-  obj = S.new
!-  arg2 = 1
!-  arg3 = 2
  a = obj.hash    # Same as
  a = obj.hash()  # this.

  obj.someMethod "Arg1", arg2, arg3   # Same thing as
  obj.someMethod("Arg1", arg2, arg3)  # with parentheses.
]]></fullcode>
a<nbsp/>=<nbsp/>obj.hash<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Same<nbsp/>as
a<nbsp/>=<nbsp/>obj.hash()<nbsp/><nbsp/>#<nbsp/>this.
<p/>
obj.someMethod<nbsp/>"Arg1",<nbsp/>arg2,<nbsp/>arg3<nbsp/><nbsp/><nbsp/>#<nbsp/>Same<nbsp/>thing<nbsp/>as
obj.someMethod("Arg1",<nbsp/>arg2,<nbsp/>arg3)<nbsp/><nbsp/>#<nbsp/>with<nbsp/>parentheses.
</alltt>
</codefragment>
<subsubsection>Expanding Arrays in Method Calls</subsubsection>
<p/>
Earlier we saw that if you put an asterisk in front of a formal
parameter in a method definition, multiple arguments in the call to the
method will be bundled up into an array. Well, the same thing works in 
reverse.
<p/>
When you call a method, you can explode an array, so that each of its
members is taken as a separate parameter. Do this by prefixing the
array argument (which must follow all the regular arguments) with an
asterisk.
<p/>
<codefragment>
<fullcode><![CDATA[  def five(a, b, c, d, e)
    "I was passed #{a} #{b} #{c} #{d} #{e}"
  end

  five(1, 2, 3, 4, 5 )
  five(1, 2, 3, *['a', 'b'])
  five(*(10..14).to_a)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>five(a,<nbsp/>b,<nbsp/>c,<nbsp/>d,<nbsp/>e)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>"I<nbsp/>was<nbsp/>passed<nbsp/>#{a}<nbsp/>#{b}<nbsp/>#{c}<nbsp/>#{d}<nbsp/>#{e}"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>five(1,<nbsp/>2,<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>)</tt></td>
  <td>&#187;</td>
  <td><tt>"I<nbsp/>was<nbsp/>passed<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>4<nbsp/>5"</tt></td>
</tr>
<tr>
  <td><tt>five(1,<nbsp/>2,<nbsp/>3,<nbsp/>*['a',<nbsp/>'b'])</tt></td>
  <td>&#187;</td>
  <td><tt>"I<nbsp/>was<nbsp/>passed<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>a<nbsp/>b"</tt></td>
</tr>
<tr>
  <td><tt>five(*(10..14).to_a)</tt></td>
  <td>&#187;</td>
  <td><tt>"I<nbsp/>was<nbsp/>passed<nbsp/>10<nbsp/>11<nbsp/>12<nbsp/>13<nbsp/>14"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsubsection>Making Blocks More Dynamic</subsubsection>
<p/>
We've already seen how you can associate a block with a method call.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-    def listBones(p)
!-    end
  listBones("aardvark") do |aBone|
    # ...
  end
]]></fullcode>
listBones("aardvark")<nbsp/>do<nbsp/>|aBone|
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
Normally, this is perfectly good enough---you associate a fixed block
of code with a method, in the same way you'd have a chunk of code
after an <kw>if</kw> or <kw>while</kw> statement.
<p/>
Sometimes, however, you'd like to be more flexible.  For example, we
may be teaching math skills.<footnote>Of course, Andy and Dave would
  have to <em>learn</em> math skills first. Conrad Schneiker   reminded us that there are three kinds
  of people: those who can count and those who can't.</footnote> The student
could ask for an <em>n</em>-plus table or an <em>n</em>-times table.  If
the student asked for a 2-times table, we'd output 2, 4, 6, 8, and
so on. (This code does not check its inputs for errors.)
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  $stdin = DATA #$
!-  $defout = File.open("/dev/null", "w")
print "(t)imes or (p)lus: "
times = gets
print "number: "
number = gets.to_i
!-  $defout = $stdout
!-  print "(t)imes or (p)lus: #{times}"
!-  print "number: #{number}\n"

if times =~ /^t/
  puts((1..10).collect { |n| n*number }.join(", "))
else
  puts((1..10).collect { |n| n+number }.join(", "))
end
!-__END__
!-t
!-2
]]></fullcode>
print<nbsp/>"(t)imes<nbsp/>or<nbsp/>(p)lus:<nbsp/>"
times<nbsp/>=<nbsp/>gets
print<nbsp/>"number:<nbsp/>"
number<nbsp/>=<nbsp/>gets.to_i
<p/>
if<nbsp/>times<nbsp/>=~<nbsp/>/^t/
<nbsp/><nbsp/>puts((1..10).collect<nbsp/>{<nbsp/>|n|<nbsp/>n*number<nbsp/>}.join(",<nbsp/>"))
else
<nbsp/><nbsp/>puts((1..10).collect<nbsp/>{<nbsp/>|n|<nbsp/>n+number<nbsp/>}.join(",<nbsp/>"))
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
(t)imes<nbsp/>or<nbsp/>(p)lus:<nbsp/>t
number:<nbsp/>2
2,<nbsp/>4,<nbsp/>6,<nbsp/>8,<nbsp/>10,<nbsp/>12,<nbsp/>14,<nbsp/>16,<nbsp/>18,<nbsp/>20
</alltt>
</codefragment>
<p/>
This works, but it's ugly, with virtually identical code on each branch
of the <kw>if</kw> statement. If would be nice if we could factor out the
block that does the calculation.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  $stdin = DATA #$
!-  $defout = File.open("/dev/null", "w")
print "(t)imes or (p)lus: "
times = gets
print "number: "
number = gets.to_i
!-  $defout = $stdout
!-  print "(t)imes or (p)lus: #{times}"
!-  print "number: #{number}\n"

if times =~ /^t/
  calc = proc { |n| n*number }
else
  calc = proc { |n| n+number }
end
puts((1..10).collect(&calc).join(", "))
!-__END__
!-t
!-2
]]></fullcode>
print<nbsp/>"(t)imes<nbsp/>or<nbsp/>(p)lus:<nbsp/>"
times<nbsp/>=<nbsp/>gets
print<nbsp/>"number:<nbsp/>"
number<nbsp/>=<nbsp/>gets.to_i
<p/>
if<nbsp/>times<nbsp/>=~<nbsp/>/^t/
<nbsp/><nbsp/>calc<nbsp/>=<nbsp/>proc<nbsp/>{<nbsp/>|n|<nbsp/>n*number<nbsp/>}
else
<nbsp/><nbsp/>calc<nbsp/>=<nbsp/>proc<nbsp/>{<nbsp/>|n|<nbsp/>n+number<nbsp/>}
end
puts((1..10).collect(&amp;calc).join(",<nbsp/>"))
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
(t)imes<nbsp/>or<nbsp/>(p)lus:<nbsp/>t
number:<nbsp/>2
2,<nbsp/>4,<nbsp/>6,<nbsp/>8,<nbsp/>10,<nbsp/>12,<nbsp/>14,<nbsp/>16,<nbsp/>18,<nbsp/>20
</alltt>
</codefragment>
<p/>
If the last argument to a method is preceded by an ampersand, Ruby
assumes that it is a <classname>Proc</classname> object. It removes it from the parameter 
list, converts the <classname>Proc</classname> object into a block, and
associates it with the method.
<p/>
This technique can also be used to add some syntactic sugar to block
usage. For example, you sometimes want to take an
iterator and store each value it yields into an array. We'll reuse our 
Fibonacci number generator from page 40.
<p/>
<codefragment>
<fullcode><![CDATA[!-def fibUpTo(max)
!-  i1, i2 = 1, 1        # parallel assignment
!-  while i1 <= max
!-    yield i1
!-    i1, i2 = i2, i1+i2
!-  end
!-end
a = []
fibUpTo(20) { |val| a << val }
a.inspect
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[]</tt></td>
</tr>
<tr>
  <td><tt>fibUpTo(20)<nbsp/>{<nbsp/>|val|<nbsp/>a<nbsp/>&lt;&lt;<nbsp/>val<nbsp/>}</tt></td>
  <td>&#187;</td>
  <td><tt>nil</tt></td>
</tr>
<tr>
  <td><tt>a.inspect</tt></td>
  <td>&#187;</td>
  <td><tt>"[1,<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>5,<nbsp/>8,<nbsp/>13]"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This works, but our intention isn't quite as transparent as we may
like. Instead, we'll define a method called <meth>into</meth>, which
returns the block that fills the array. (Notice at the same time that 
the block returned really is a closure---it references the parameter
<obj>anArray</obj> even after method <meth>into</meth> has returned.)
<p/>
<codefragment>
<fullcode><![CDATA[!-def fibUpTo(max)
!-  i1, i2 = 1, 1        # parallel assignment
!-  while i1 <= max
!-    yield i1
!-    i1, i2 = i2, i1+i2
!-  end
!-end
def into(anArray)
  return proc { |val| anArray << val }
end

fibUpTo 20, &into(a = [])
a.inspect
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>into(anArray)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>return<nbsp/>proc<nbsp/>{<nbsp/>|val|<nbsp/>anArray<nbsp/>&lt;&lt;<nbsp/>val<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>fibUpTo<nbsp/>20,<nbsp/>&amp;into(a<nbsp/>=<nbsp/>[])</tt></td>
</tr>
<tr>
  <td><tt>a.inspect</tt></td>
  <td>&#187;</td>
  <td><tt>"[1,<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>5,<nbsp/>8,<nbsp/>13]"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsubsection>Collecting Hash Arguments</subsubsection>
<p/>
Some languages feature ``keyword arguments''---that is, instead of
passing arguments in a given order and quantity, you pass the name
of the argument with its value, in any order.  Ruby 1.6 does not have
keyword arguments (although they are scheduled to be implemented in
Ruby 1.8).
<p/>
In the meantime, people are using hashes as a way of achieving the
same effect. For example, we might consider adding a more powerful
named-search facility to our <classname>SongList</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
  def createSearch(name, params)
    # ...
  end
end  
!-aList = SongList.new
aList.createSearch("short jazz songs", {
                   'genre'            => "jazz",
                   'durationLessThan' => 270
                   } )
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>createSearch(name,<nbsp/>params)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>end
end
aList.createSearch("short<nbsp/>jazz<nbsp/>songs",<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'genre'<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>"jazz",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'durationLessThan'<nbsp/>=&gt;<nbsp/>270
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>}<nbsp/>)
</alltt>
</codefragment>
<p/>
The first parameter is the search name, and the second is a hash literal
containing search parameters. The use of a hash means that we can
simulate keywords: look for songs with a genre of ``jazz'' and a
duration less than  4 1/2  minutes. However, this approach is
slightly clunky, and that set of braces could easily be mistaken for a 
block associated with the method. So, Ruby has a short cut. You can
place <obj>key</obj><nbsp/><tt>=&gt;</tt><nbsp/><obj>value</obj> pairs in an argument list, as long 
as they follow any normal arguments and precede any array and block
arguments. All these pairs will be collected into a single hash and
passed as one argument to the method. No braces are needed.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class WordIndex
!-    def initialize
!-      @index = Hash.new(nil)
!-    end
!-    def index(anObject, *phrases)
!-      phrases.each do |aPhrase|
!-        aPhrase.scan /\w[-\w']+/ do |aWord|   # extract each word
!-          aWord.downcase!
!-          @index[aWord] = [] if @index[aWord].nil?
!-          @index[aWord].push(anObject)
!-        end
!-      end
!-    end
!-    def lookup(aWord)
!-      @index[aWord.downcase]
!-    end
!-  end
!-class SongList
!-  def initialize
!-    @songs = Array.new
!-    @index = WordIndex.new
!-  end
!-  def append(aSong)
!-    @songs.push(aSong)
!-    @index.index(aSong, aSong.name, aSong.artist)
!-    self
!-  end
!-  def deleteFirst
!-    @songs.shift
!-  end
!-  def deleteLast
!-    @songs.pop
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      @songs[key]
!-    else
!-      # ...
!-    end
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      return @songs[key]
!-    else
!-      for i in 0...@songs.length
!-        return @songs[i] if key == @songs[i].name
!-      end
!-    end
!-    return nil
!-  end
!-  def [](key)
!-    if key.kind_of?(Integer)
!-      result = @songs[key]
!-    else
!-      result = @songs.find { |aSong| key == aSong.name }
!-    end
!-    return result
!-  end
!-  def lookup(aWord)
!-    @index.lookup(aWord)
!-  end
!-  def createSearch(name, params)
!-    # ...
!-  end
!-end  
!-aList = SongList.new
aList.createSearch("short jazz songs",
                   'genre'            => "jazz",
                   'durationLessThan' => 270
                   )
]]></fullcode>
aList.createSearch("short<nbsp/>jazz<nbsp/>songs",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'genre'<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=&gt;<nbsp/>"jazz",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'durationLessThan'<nbsp/>=&gt;<nbsp/>270
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>)
</alltt>
</codefragment>
<p/>
</chapter>
</ppdoc>
