1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
|
<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 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>»</td>
<td><tt>"Miles,<nbsp/>Coltrane,<nbsp/>Roach."</tt></td>
</tr>
<tr>
<td><tt>coolDude("Bart")</tt></td>
<td>»</td>
<td><tt>"Bart,<nbsp/>Coltrane,<nbsp/>Roach."</tt></td>
</tr>
<tr>
<td><tt>coolDude("Bart",<nbsp/>"Elwood")</tt></td>
<td>»</td>
<td><tt>"Bart,<nbsp/>Elwood,<nbsp/>Roach."</tt></td>
</tr>
<tr>
<td><tt>coolDude("Bart",<nbsp/>"Elwood",<nbsp/>"Linus")</tt></td>
<td>»</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>»</td>
<td><tt>"Got<nbsp/>one<nbsp/>and<nbsp/>"</tt></td>
</tr>
<tr>
<td><tt>varargs("one",<nbsp/>"two")</tt></td>
<td>»</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>»</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 40, 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>»</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>»</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/>&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>»</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>»</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>»</td>
<td><tt>537712200</tt></td>
</tr>
<tr>
<td><tt>id</tt></td>
<td>»</td>
<td><tt>537712200</tt></td>
</tr>
<tr>
<td><tt>self.type</tt></td>
<td>»</td>
<td><tt>Object</tt></td>
</tr>
<tr>
<td><tt>type</tt></td>
<td>»</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>»</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>»</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>»</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(&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 42.
<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/><<<nbsp/>val<nbsp/>}</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
<tr>
<td><tt>a.inspect</tt></td>
<td>»</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/><<<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/>&into(a<nbsp/>=<nbsp/>[])</tt></td>
</tr>
<tr>
<td><tt>a.inspect</tt></td>
<td>»</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/>=><nbsp/>"jazz",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'durationLessThan'<nbsp/>=><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>=></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/>=><nbsp/>"jazz",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'durationLessThan'<nbsp/>=><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>
|