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
|
<html><title>Programming Ruby: The Pragmatic Programmer's Guide</title><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><STYLE TYPE="text/css"><!--
BODY { margin-left: 1in;
width: 6in;
font-family: helvetica, arial, sans-serif;
}
H1 { color: #000080;
font-family: helvetica, arial, sans-serif;
font-size: 22pt;
margin-left: 0in
}
H2 { color: #000080; font: bold x-large helvetica, sans-serif;
margin-left: 0in }
H3 { color: #000080; font: bold large helvetica, sans-serif; }
H4 { color: #000080; font: italic large helvetica, sans-serif; }
.ruby { background: #fff0f0 }
.header { color: white }
.subheader { color: #ffdddd }
.sidebar { width: 6in }
span.sans { font-family: helvetica, arial, sans-serif }
-->
</STYLE><table bgcolor="#a03030" cellpadding="3" border="0" cellspacing="0"><tr><td colspan="3"><table bgcolor="#902020" cellpadding="20"><tr><td><h1 class="header">Programming Ruby</h1><h3 class="subheader">The Pragmatic Programmer's Guide</h3></td></tr></table></td></tr><tr><td width="33%" align="left"><a class="subheader" href="tut_stdtypes.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_expressions.html">Next ></a><br></td></tr></table></head><body bgcolor="white">
<!--
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/).
-->
<h1>More About Methods</h1><hr><br>
<P></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></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.
<h2>Defining a Method</h2>
<P></P>
As we've seen throughout this book, a method is defined using the
keyword <code>def</code>.
Method names should begin with a lowercase
letter.<em>[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.]</em> Methods that act as
queries are often named with a trailing ``<code>?</code>'', such as
<code>instance_of?</code>. Methods that are ``dangerous,'' or modify the
receiver, might be named with a trailing ``<code>!</code>''. For instance,
<code>String</code> provides both a <code>chop</code> and a <code>chop!</code>. The first one
returns a modified string; the second modifies the receiver in
place. ``<code>?</code>'' and ``<code>!</code>'' are the only weird characters allowed
as method name suffixes.
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def myNewMethod(arg1, arg2, arg3) # 3 arguments
# Code for the method would go here
end
<P></P>
def myOtherNewMethod # No arguments
# Code for the method would go here
end
</pre></td></tr></table>
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def coolDude(arg1="Miles", arg2="Coltrane", arg3="Roach")</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "#{arg1}, #{arg2}, #{arg3}."</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>coolDude</code></td>
<td valign="top"></td>
<td valign="top"><code>"Miles, Coltrane, Roach."</code></td>
</tr>
<tr>
<td valign="top"><code>coolDude("Bart")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Bart, Coltrane, Roach."</code></td>
</tr>
<tr>
<td valign="top"><code>coolDude("Bart", "Elwood")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Bart, Elwood, Roach."</code></td>
</tr>
<tr>
<td valign="top"><code>coolDude("Bart", "Elwood", "Linus")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Bart, Elwood, Linus."</code></td>
</tr>
</table>
<P></P>
<P></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 <code>return</code> expression.
<h3>Variable-Length Argument Lists</h3>
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def varargs(arg1, *rest)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "Got #{arg1} and #{rest.join(', ')}"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>varargs("one")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Got one and "</code></td>
</tr>
<tr>
<td valign="top"><code>varargs("one", "two")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Got one and two"</code></td>
</tr>
<tr>
<td valign="top"><code>varargs "one", "two", "three"</code></td>
<td valign="top"></td>
<td valign="top"><code>"Got one and two, three"</code></td>
</tr>
</table>
<P></P>
<P></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
<code>Array</code>, which is then assigned to that parameter.
<h3>Methods and Blocks</h3>
<P></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
<code>yield</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def takeBlock(p1)
if block_given?
yield(p1)
else
p1
end
end
</pre></td></tr></table>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>takeBlock("no block")</code></td>
<td valign="top"></td>
<td valign="top"><code>"no block"</code></td>
</tr>
<tr>
<td valign="top"><code>takeBlock("no block") { |s| s.sub(/no /, '') }</code></td>
<td valign="top"></td>
<td valign="top"><code>"block"</code></td>
</tr>
</table>
<P></P>
<P></P>
However, if the last parameter in a method definition is
prefixed with an ampersand, any associated block is converted to a
<code>Proc</code> object, and that object is assigned to the parameter.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class TaxCalculator</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def initialize(name, &block)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @name, @block = name, block</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def getTax(amount)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "#@name on #{amount} = #{ @block.call(amount) }"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>tc = TaxCalculator.new("Sales tax") { |amt| amt * 0.075 }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>tc.getTax(100)</code></td>
<td valign="top"></td>
<td valign="top"><code>"Sales tax on 100 = 7.5"</code></td>
</tr>
<tr>
<td valign="top"><code>tc.getTax(250)</code></td>
<td valign="top"></td>
<td valign="top"><code>"Sales tax on 250 = 18.75"</code></td>
</tr>
</table>
<P></P>
<h2>Calling a Method</h2>
<P></P>
You call a method by specifying a receiver, the name of the method,
and optionally some parameters and an associated block.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
connection.downloadMP3("jitterbug") { |p| showProgress(p) }
</pre></td></tr></table>
<P></P>
In this example, the object <code>connection</code> is the receiver,
<code>downloadMP3</code> is the name of the method, <code>"jitterbug"</code> is
the parameter, and the stuff between the braces is the associated
block.
<P></P>
For class and module methods, the receiver will be the class or module
name.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
File.size("testfile")
Math.sin(Math::PI/4)
</pre></td></tr></table>
<P></P>
If you omit the receiver, it defaults to <code>self</code>, the current
object.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>self.id</code></td>
<td valign="top"></td>
<td valign="top"><code>537712200</code></td>
</tr>
<tr>
<td valign="top"><code>id</code></td>
<td valign="top"></td>
<td valign="top"><code>537712200</code></td>
</tr>
<tr>
<td valign="top"><code>self.type</code></td>
<td valign="top"></td>
<td valign="top"><code>Object</code></td>
</tr>
<tr>
<td valign="top"><code>type</code></td>
<td valign="top"></td>
<td valign="top"><code>Object</code></td>
</tr>
</table>
<P></P>
<P></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></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.<em>[Other Ruby documentation sometimes calls
these method calls without parentheses ``commands.'']</em> However,
except in the simplest cases we don't recommend this---there are some
subtle problems that can trip you up.<em>[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).]</em>
Our rule is simple: if there's any doubt, use parentheses.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
a = obj.hash # Same as
a = obj.hash() # this.
<P></P>
obj.someMethod "Arg1", arg2, arg3 # Same thing as
obj.someMethod("Arg1", arg2, arg3) # with parentheses.
</pre></td></tr></table>
<h3>Expanding Arrays in Method Calls</h3>
<P></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></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def five(a, b, c, d, e)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "I was passed #{a} #{b} #{c} #{d} #{e}"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>five(1, 2, 3, 4, 5 )</code></td>
<td valign="top"></td>
<td valign="top"><code>"I was passed 1 2 3 4 5"</code></td>
</tr>
<tr>
<td valign="top"><code>five(1, 2, 3, *['a', 'b'])</code></td>
<td valign="top"></td>
<td valign="top"><code>"I was passed 1 2 3 a b"</code></td>
</tr>
<tr>
<td valign="top"><code>five(*(10..14).to_a)</code></td>
<td valign="top"></td>
<td valign="top"><code>"I was passed 10 11 12 13 14"</code></td>
</tr>
</table>
<P></P>
<h3>Making Blocks More Dynamic</h3>
<P></P>
We've already seen how you can associate a block with a method call.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
listBones("aardvark") do |aBone|
# ...
end
</pre></td></tr></table>
<P></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 <code>if</code> or <code>while</code> statement.
<P></P>
Sometimes, however, you'd like to be more flexible. For example, we
may be teaching math skills.<em>[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.]</em> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
print "(t)imes or (p)lus: "
times = gets
print "number: "
number = gets.to_i
<P></P>
if times =~ /^t/
puts((1..10).collect { |n| n*number }.join(", "))
else
puts((1..10).collect { |n| n+number }.join(", "))
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
(t)imes or (p)lus: t
number: 2
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
</pre></td></tr></table>
<P></P>
This works, but it's ugly, with virtually identical code on each branch
of the <code>if</code> statement. If would be nice if we could factor out the
block that does the calculation.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
print "(t)imes or (p)lus: "
times = gets
print "number: "
number = gets.to_i
<P></P>
if times =~ /^t/
calc = proc { |n| n*number }
else
calc = proc { |n| n+number }
end
puts((1..10).collect(&calc).join(", "))
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
(t)imes or (p)lus: t
number: 2
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
</pre></td></tr></table>
<P></P>
If the last argument to a method is preceded by an ampersand, Ruby
assumes that it is a <code>Proc</code> object. It removes it from the parameter
list, converts the <code>Proc</code> object into a block, and
associates it with the method.
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = []</code></td>
</tr>
<tr>
<td valign="top"><code>fibUpTo(20) { |val| a << val }</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
<tr>
<td valign="top"><code>a.inspect</code></td>
<td valign="top"></td>
<td valign="top"><code>"[1, 1, 2, 3, 5, 8, 13]"</code></td>
</tr>
</table>
<P></P>
<P></P>
This works, but our intention isn't quite as transparent as we may
like. Instead, we'll define a method called <code>into</code>, 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
<i>anArray</i> even after method <code>into</code> has returned.)
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def into(anArray)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> return proc { |val| anArray << val }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>fibUpTo 20, &into(a = [])</code></td>
</tr>
<tr>
<td valign="top"><code>a.inspect</code></td>
<td valign="top"></td>
<td valign="top"><code>"[1, 1, 2, 3, 5, 8, 13]"</code></td>
</tr>
</table>
<P></P>
<h3>Collecting Hash Arguments</h3>
<P></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></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 <code>SongList</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def createSearch(name, params)
# ...
end
end
aList.createSearch("short jazz songs", {
'genre' => "jazz",
'durationLessThan' => 270
} )
</pre></td></tr></table>
<P></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 <i>key</i> <code>=></code> <i>value</i> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
aList.createSearch("short jazz songs",
'genre' => "jazz",
'durationLessThan' => 270
)
</pre></td></tr></table>
<P></P>
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="tut_stdtypes.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_expressions.html">Next ></a><br></td></tr></table><p></p><font size="-1">Extracted from the book "Programming Ruby -
The Pragmatic Programmer's Guide"</font><br><font size="-3">
Copyright
©
2000 Addison Wesley Longman, Inc. Released under the terms of the
<a href="http://www.opencontent.org/openpub/">Open Publication License</a> V1.0.
<br>
This reference is available for
<a href="http://www.pragmaticprogrammer.com/ruby/downloads/book.html">download</a>.
</font></body></html>
|