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 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
|
<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_methods.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_exceptions.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>Expressions</h1><hr><br>
<P></P>
So far we've been fairly cavalier in our use of expressions in Ruby.
After all, <code>a=b+c</code> is pretty standard
stuff. You could write a whole heap of Ruby code without reading any
of this chapter.
<P></P>
But it wouldn't be as much fun <code>;-)</code>.
<P></P>
One of the first differences with Ruby is that anything that can
reasonably return a value does: just about everything is an
expression. What does this mean in practice?
<P></P>
Some obvious things include the ability to chain statements together.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>a = b = c = 0</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td valign="top"><code>[ 3, 1, 7, 0 ].sort.reverse</code></td>
<td valign="top"></td>
<td valign="top"><code>[7, 3, 1, 0]</code></td>
</tr>
</table>
<P></P>
<P></P>
Perhaps less obvious, things that are normally statements in C
or Java are expressions in Ruby. For example, the <code>if</code> and
<code>case</code> statements both return the value of the last expression
executed.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songType = if song.mp3Type == MP3::Jazz
if song.written < Date.new(1935, 1, 1)
Song::TradJazz
else
Song::Jazz
end
else
Song::Other
end
<P></P>
rating = case votesCast
when 0...10 then Rating::SkipThisOne
when 10...50 then Rating::CouldDoBetter
else Rating::Rave
end
</pre></td></tr></table>
<P></P>
We'll talk more about <code>if</code> and <code>case</code> starting
on page 81.
<h2>Operator Expressions</h2>
<P></P>
Ruby has the basic set of operators (+, -, *, /, and so on) as well
as a few surprises. A complete list of the operators, and their
precedences, is given in Table 18.4 on page 221.
<P></P>
In Ruby, many operators are actually method calls. When you write
<code>a*b+c</code>
you're actually asking the object referenced by <code>a</code> to execute the
method ``<code>*</code>'', passing in the parameter <code>b</code>. You then ask the
object that results from that calculation to execute ``<code>+</code>'',
passing <code>c</code> as a parameter. This is exactly equivalent
to writing
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
(a.*(b)).+(c)
</pre></td></tr></table>
<P></P>
Because everything is an object, and because you can redefine
instance methods, you can always redefine basic arithmetic if you
don't like the answers you're getting.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Fixnum</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> alias oldPlus +</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def +(other)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> oldPlus(other).succ</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 valign="top"><code>1 + 2</code></td>
<td valign="top"></td>
<td valign="top"><code>4</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a = 3</code></td>
</tr>
<tr>
<td valign="top"><code>a += 4</code></td>
<td valign="top"></td>
<td valign="top"><code>8</code></td>
</tr>
</table>
<P></P>
<P></P>
More useful is the fact that classes that you write can participate in
operator expressions just as if they were built-in objects. For
example, we might want to be able to extract a number of seconds of
music from the middle of a song. We could using the indexing operator
``<code>[]</code>'' to specify the music to be extracted.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Song
def [](fromTime, toTime)
result = Song.new(self.title + " [extract]",
self.artist,
toTime - fromTime)
result.setStartTime(fromTime)
result
end
end
</pre></td></tr></table>
<P></P>
This code fragment extends class <code>Song</code> with the method
``<code>[]</code>'', which takes two parameters (a start time and an end
time). It returns a new song, with the music clipped to the given
interval. We could then play the introduction to a song with code
such as:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
aSong[0, 0.15].play
</pre></td></tr></table>
<h2>Miscellaneous Expressions</h2>
<P></P>
As well as the obvious operator expressions and method calls, and the
(perhaps) less obvious statement expressions (such as <code>if</code> and
<code>case</code>), Ruby has a few more things that you can use in
expressions.
<h3>Command Expansion</h3>
<P></P>
If you enclose a string in backquotes, or use the delimited form
prefixed by <code>%x</code>, it will (by default) be executed as a command by
your underlying operating system.
The value of the expression is the
standard output of that command. Newlines will not be stripped, so it is
likely that the value you get back will have a trailing return or
linefeed character.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>`date`</code></td>
<td valign="top"></td>
<td valign="top"><code>"Sun Mar 4 23:23:52 CST 2001\n"</code></td>
</tr>
<tr>
<td valign="top"><code>`dir`.split[34]</code></td>
<td valign="top"></td>
<td valign="top"><code>"lib_pstore.txi"</code></td>
</tr>
<tr>
<td valign="top"><code>%x{echo "Hello there"}</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hello there\n"</code></td>
</tr>
</table>
<P></P>
<P></P>
You can use expression expansion and all the usual escape sequences in
the command string.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
for i in 0..3
status = `dbmanager status id=#{i}`
# ...
end
</pre></td></tr></table>
<P></P>
The exit status of the command is available in the global variable
<code>$?</code>.
<h3>Backquotes Are Soft</h3>
<P></P>
In the description of the command output expression, we said that the
string in backquotes would ``by default'' be executed as a command. In
fact, the string is passed to the method called <a href="ref_m_kernel.html#_bq"><code>Kernel::`</code></a>
(a single backquote). If you want, you can override
this.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
alias oldBackquote `
def `(cmd)
result = oldBackquote(cmd)
if $? != 0
raise "Command #{cmd} failed"
end
result
end
print `date`
print `data`
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Sun Mar 4 23:23:52 CST 2001
prog.rb:3: command not found: data
prog.rb:5:in ``': Command data failed (RuntimeError)
from prog.rb:10
</pre></td></tr></table>
<h2>Assignment</h2>
<P></P>
Just about every example we've given so far in this book has featured
assignment. Perhaps it's about time we said something about it.
<P></P>
An assignment statement sets the variable or attribute on its left
side (the <em>lvalue</em>) to refer to the value on the right (the
<em>rvalue</em>).
It then returns that value as the result of the
assignment expression. This means that you can chain assignments and
that you can
perform assignments in some unexpected places.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = b = 1 + 2 + 3</code></td>
</tr>
<tr>
<td valign="top"><code>a</code></td>
<td valign="top"></td>
<td valign="top"><code>6</code></td>
</tr>
<tr>
<td valign="top"><code>b</code></td>
<td valign="top"></td>
<td valign="top"><code>6</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a = (b = 1 + 2) + 3</code></td>
</tr>
<tr>
<td valign="top"><code>a</code></td>
<td valign="top"></td>
<td valign="top"><code>6</code></td>
</tr>
<tr>
<td valign="top"><code>b</code></td>
<td valign="top"></td>
<td valign="top"><code>3</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>File.open(name = gets.chomp)</code></td>
</tr>
</table>
<P></P>
<P></P>
There are two basic forms of assignment in Ruby. The first assigns an
object reference to a variable or constant. This form of assignment
is hard-wired into the language.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
instrument = "piano"
MIDDLE_A = 440
</pre></td></tr></table>
<P></P>
The second form of assignment involves having an object attribute or
element reference on the left-hand side.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
aSong.duration = 234
instrument["ano"] = "ccolo"
</pre></td></tr></table>
<P></P>
These forms are special, because they are implemented by calling
methods in the lvalues, which means you can override them.
<P></P>
We've already seen how to define a writable object attribute. Simply
define a method name ending in an equals sign. This method receives as
its parameter the assignment's rvalue.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Song
def duration=(newDuration)
@duration = newDuration
end
end
</pre></td></tr></table>
<P></P>
There is no reason that these attribute setting methods must
correspond with internal instance variables, or that there has to be
an attribute reader for every attribute writer (or vice versa).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Amplifier
def volume=(newVolume)
self.leftChannel = self.rightChannel = newVolume
end
# ...
end
</pre></td></tr></table>
<P></P>
<p></p><table width="500" border="2" cellpadding="15" bgcolor="#ffe0e0" align="center"><tr><td align="center"><b>Sidebar: Using Accessors Within a Class</b></td></tr><tr><td>
<P></P>
Why did we write <code>self.leftChannel</code> in the example on page
76? Well, there's a hidden gotcha with writable
attributes. Normally, methods within a class can invoke other
methods in the same class and its superclasses in functional form
(that is, with an implicit receiver of <code>self</code>). However, this
doesn't work with attribute writers. Ruby sees the assignment and
decides that the name on the left must be a local variable, not a
method call to an attribute writer.
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class BrokenAmplifier</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> attr_accessor :leftChannel, :rightChannel</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def volume=(vol)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> leftChannel = self.rightChannel = vol</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>ba = BrokenAmplifier.new</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>ba.leftChannel = ba.rightChannel = 99</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>ba.volume = 5</code></td>
</tr>
<tr>
<td valign="top"><code>ba.leftChannel</code></td>
<td valign="top"></td>
<td valign="top"><code>99</code></td>
</tr>
<tr>
<td valign="top"><code>ba.rightChannel</code></td>
<td valign="top"></td>
<td valign="top"><code>5</code></td>
</tr>
</table>
<P></P>
We forgot to put ``<code>self.</code>'' in front of the assignment to
<code>leftChannel</code>, so Ruby stored the new value in a local variable of
method <code>volume=</code>; the object's attribute never got updated.
This can be a tricky bug to track down.
<P></P>
</td></tr></table><p></p>
<h3>Parallel Assignment</h3>
<P></P>
During your first week in a programming course (or the second semester
if it was a party school), you may have had to write code to swap the
values in two variables:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
int a = 1;
int b = 2;
int temp;
<P></P>
temp = a;
a = b;
b = temp;
</pre></td></tr></table>
<P></P>
You can do this much more cleanly in Ruby:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
a, b = b, a
</pre></td></tr></table>
<P></P>
Ruby assignments are effectively performed in parallel, so the values
assigned are not affected by the assignment itself. The values on the
right-hand side are evaluated in the order in which they appear before any
assignment is made to variables or attributes on the left. A somewhat
contrived example illustrates this. The second line assigns to the
variables <code>a</code>, <code>b</code>, and <code>c</code> the values of the expressions
<code>x</code>, <code>x+=1</code>, and <code>x+=1</code>, respectively.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>x = 0</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td valign="top"><code>a, b, c = x, (x += 1), (x += 1)</code></td>
<td valign="top"></td>
<td valign="top"><code>[0, 1, 2]</code></td>
</tr>
</table>
<P></P>
<P></P>
When an assignment has more than one lvalue, the assignment expression
returns an array of the rvalues.
If an assignment contains more lvalues than rvalues, the excess
lvalues are
set to <code>nil</code>. If a multiple assignment contains more rvalues than
lvalues, the extra rvalues are ignored. As of Ruby 1.6.2, if an
assignment has one lvalue and multiple rvalues, the rvalues are
converted to an array and assigned to the lvalue.
<P></P>
You can collapse and expand arrays using Ruby's parallel assignment
operator. If the last lvalue is preceded by an asterisk, all the
remaining rvalues will be collected and assigned to that lvalue as an
array. Similarly, if the last rvalue is an array, you can prefix it
with an asterisk, which effectively expands it into its constituent
values in place. (This is not necessary if the rvalue is the only
thing on the right-hand side---the array will be expanded
automatically.)
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr>
<td colspan="4" valign="top"><code>a = [1, 2, 3, 4]</code></td>
</tr>
<tr>
<td valign="top">b, c = a</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2</td>
</tr>
<tr>
<td valign="top">b, *c = a</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == [2, 3, 4]</td>
</tr>
<tr>
<td valign="top">b, c = 99, a</td>
<td valign="top"> </td>
<td valign="top">b == 99,</td>
<td valign="top">c == [1, 2, 3, 4]</td>
</tr>
<tr>
<td valign="top">b, *c = 99, a</td>
<td valign="top"> </td>
<td valign="top">b == 99,</td>
<td valign="top">c == [[1, 2, 3, 4]]</td>
</tr>
<tr>
<td valign="top">b, c = 99, *a</td>
<td valign="top"> </td>
<td valign="top">b == 99,</td>
<td valign="top">c == 1</td>
</tr>
<tr>
<td valign="top">b, *c = 99, *a</td>
<td valign="top"> </td>
<td valign="top">b == 99,</td>
<td valign="top">c == [1, 2, 3, 4]</td>
</tr>
</table>
<P></P>
<h3>Nested Assignments</h3>
<P></P>
Parallel assignments have one more feature worth mentioning.
The left-hand side of an assignment may contain a parenthesized list of
terms. Ruby treats these terms as if they were a nested assignment
statement. It extracts out the corresponding rvalue, assigning it to
the parenthesized terms, before continuing with the higher-level
assignment.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr>
<td valign="top">b, (c, d), e = 1,2,3,4</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2,</td>
<td valign="top">d == nil,</td>
<td valign="top">e == 3</td>
</tr>
<tr>
<td valign="top">b, (c, d), e = [1,2,3,4]</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2,</td>
<td valign="top">d == nil,</td>
<td valign="top">e == 3</td>
</tr>
<tr>
<td valign="top">b, (c, d), e = 1,[2,3],4</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2,</td>
<td valign="top">d == 3,</td>
<td valign="top">e == 4</td>
</tr>
<tr>
<td valign="top">b, (c, d), e = 1,[2,3,4],5</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2,</td>
<td valign="top">d == 3,</td>
<td valign="top">e == 5</td>
</tr>
<tr>
<td valign="top">b, (c,*d), e = 1,[2,3,4],5</td>
<td valign="top"> </td>
<td valign="top">b == 1,</td>
<td valign="top">c == 2,</td>
<td valign="top">d == [3, 4],</td>
<td valign="top">e == 5</td>
</tr>
</table>
<P></P>
<h3>Other Forms of Assignment</h3>
<P></P>
In common with many other languages, Ruby has a syntactic shortcut:
<code>a=a+2</code> may be written as <code>a+=2</code>.
<P></P>
The second form is converted internally to the first. This means that
operators that you have defined as methods in your own classes work as
you'd expect.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Bowdlerize</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def initialize(aString)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @value = aString.gsub(/[aeiou]/, '*')</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def +(other)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> Bowdlerize.new(self.to_s + other.to_s)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @value</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 valign="top"><code>a = Bowdlerize.new("damn ")</code></td>
<td valign="top"></td>
<td valign="top"><code>d*mn</code></td>
</tr>
<tr>
<td valign="top"><code>a += "shame"</code></td>
<td valign="top"></td>
<td valign="top"><code>d*mn sh*m*</code></td>
</tr>
</table>
<P></P>
<h2>Conditional Execution</h2>
<P></P>
Ruby has several different mechanisms for conditional execution of
code; most of them should feel familiar, and many have some neat
twists. Before we get into them, though, we need to spend a short time
looking at boolean expressions.
<h3>Boolean Expressions</h3>
<P></P>
Ruby has a simple definition of truth. Any value that is not <code>nil</code> or
the constant <code>false</code> is true. You'll find that the library
routines use this fact consistently. For example, <a href="ref_c_io.html#gets"><code>IO#gets</code></a>,
which returns the next line from a file, returns <code>nil</code> at end of
file, enabling you to write loops such as:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
while line = gets
# process line
end
</pre></td></tr></table>
<P></P>
However, there's a trap here for C, C++, and Perl
programmers. The number zero is <em>not</em> interpreted as a false
value. Neither is a zero-length string. This can be a tough habit to
break.
<h3>Defined?, And, Or, and Not</h3>
<P></P>
Ruby supports all the standard boolean operators and introduces the
new operator <code>defined?</code>.
<P></P>
Both ``<code>and</code>'' and ``<code>&&</code>''
evaluate to true only if both operands are
true. They evaluate the second operand only if the first is true
(this is sometimes known as ``short-circuit evaluation''). The only
difference in the two forms is precedence (``<code>and</code>'' binds lower than
``<code>&&</code>'').
<P></P>
Similarly, both ``<code>or</code>'' and ``<code>||</code>''
evaluate to true if either operand
is true. They evaluate their second operand only if the first is
false. As with ``<code>and</code>'', the only difference between ``<code>or</code>'' and
``<code>||</code>'' is their precedence.
<P></P>
Just to make life interesting, ``<code>and</code>'' and ``<code>or</code>'' have the
same precedence, while ``<code>&&</code>'' has a higher precedence than
``<code>||</code>''.
<P></P>
``<code>not</code>'' and ``<code>!</code>''
return the opposite of their operand (false if the
operand is true, and true if the operand is false). And, yes, ``<code>not</code>''
and ``<code>!</code>'' differ only in precedence.
<P></P>
All these precedence rules are summarized in Table
18.4 on page 221.
<P></P>
The <code>defined?</code>
operator returns <code>nil</code> if its argument (which can be
an arbitrary expression) is not defined, otherwise it returns a
description of that argument. If the argument is <code>yield</code>,
<code>defined?</code> returns the string ``yield'' if a code block is
associated with the current context.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>defined? 1</code></td>
<td valign="top"></td>
<td valign="top"><code>"expression"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? dummy</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
<tr>
<td valign="top"><code>defined? printf</code></td>
<td valign="top"></td>
<td valign="top"><code>"method"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? String</code></td>
<td valign="top"></td>
<td valign="top"><code>"constant"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? $&</code></td>
<td valign="top"></td>
<td valign="top"><code>"$&"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? $_</code></td>
<td valign="top"></td>
<td valign="top"><code>"global-variable"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? Math::PI</code></td>
<td valign="top"></td>
<td valign="top"><code>"constant"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? ( c,d = 1,2 )</code></td>
<td valign="top"></td>
<td valign="top"><code>"assignment"</code></td>
</tr>
<tr>
<td valign="top"><code>defined? 42.abs</code></td>
<td valign="top"></td>
<td valign="top"><code>"method"</code></td>
</tr>
</table>
<P></P>
<P></P>
In addition to the boolean operators, Ruby objects support comparison
using the methods <code>==</code>, <code>===</code>, <code><=></code>, <code>=~</code>, <code>eql?</code>,
and <code>equal?</code> (see Table 7.1 on page 81). All but <code><=></code>
are defined in class <code>Object</code> but are often overridden by
descendents to provide appropriate semantics. For example, class
<code>Array</code> redefines <code>==</code> so that two array objects are equal if
they have the same number of elements and corresponding elements are
equal.
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>
<b>Common comparison operators</b>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr bgcolor="#ff9999">
<td valign="top"><b>Operator</b></td>
<td valign="top"><b>Meaning</b></td>
</tr>
<tr>
<td valign="top"><code>==</code></td>
<td valign="top">Test for equal value.</td>
</tr>
<tr>
<td valign="top"><code>===</code></td>
<td valign="top">Used to test equality within a <code>when</code> clause of a
<code>case</code> statement.</td>
</tr>
<tr>
<td valign="top"><code><=></code></td>
<td valign="top">General comparison operator. Returns -1, 0, or +1,
depending on whether its receiver is less than, equal to, or
greater than its argument.</td>
</tr>
<tr>
<td valign="top"><code><</code>, <code><=</code>, <code>>=</code>, <code>></code></td>
<td valign="top">Comparison operators for less than, less than or
equal, greater than or equal, and greater than.</td>
</tr>
<tr>
<td valign="top"><code>=~</code></td>
<td valign="top">Regular expression pattern match.</td>
</tr>
<tr>
<td valign="top"><code>eql?</code></td>
<td valign="top">True if the receiver and argument have both the same
type and equal values. 1 == 1.0 returns <code>true</code>,
but 1.eql?(1.0) is <code>false</code>.</td>
</tr>
<tr>
<td valign="top"><code>equal?</code></td>
<td valign="top">True if the receiver and argument have the same
object id.</td>
</tr>
<tr><td colspan="9" bgcolor="#ff9999" height="2"><img src="dot.gif" width="1" height="1"></td></tr></table>
<P></P>
</td></tr></table>
<P></P>
Both <code>==</code> and <code>=~</code> have negated forms, <code>!=</code> and <code>!~</code>.
However, these are converted by Ruby when your program is read.
<code>a!=b</code> is equivalent to <code>!(a==b)</code>,
and <code>a!~b</code> is the
same as <code>!(a=~b)</code>. This means that if you write a class that
overrides <code>==</code> or <code>=~</code> you get a working <code>!=</code> and <code>!~</code>
for free. But on the flip side, this also means that you cannot define
<code>!=</code> and <code>!~</code> independent of <code>==</code> and <code>=~</code>, respectively.
<P></P>
You can use a Ruby range as a boolean expression.
A
range such as <code>exp1..exp2</code> will evaluate as false
until <code>exp1</code> becomes true. The range will then evaluate as true
until <code>exp2</code> becomes true. Once this happens, the range resets,
ready to fire again. We show some examples of this
on page 84.
<P></P>
Finally, you can use a bare regular expression as a boolean
expression. Ruby expands it to <code>$_=~/re/</code>.
<h3>If and Unless Expressions</h3>
<P></P>
An <code>if</code> expression in Ruby is pretty similar to ``if'' statements
in other languages.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
if aSong.artist == "Gillespie" then
handle = "Dizzy"
elsif aSong.artist == "Parker" then
handle = "Bird"
else
handle = "unknown"
end
</pre></td></tr></table>
<P></P>
If you lay out your <code>if</code> statements on multiple lines, you can
leave off the <code>then</code> keyword.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
if aSong.artist == "Gillespie"
handle = "Dizzy"
elsif aSong.artist == "Parker"
handle = "Bird"
else
handle = "unknown"
end
</pre></td></tr></table>
<P></P>
However, if you lay your code out more tightly, the <code>then</code> keyword
is necessary to separate the boolean expression from the following
statements.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
if aSong.artist == "Gillespie" then handle = "Dizzy"
elsif aSong.artist == "Parker" then handle = "Bird"
else handle = "unknown"
end
</pre></td></tr></table>
<P></P>
You can have zero or more <code>elsif</code> clauses and an optional
<code>else</code> clause.
<P></P>
As we've said before, <code>if</code> is
an expression, not a statement---it returns a value. You don't have
to use the value of an <code>if</code> expression, but it can come in handy.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
handle = if aSong.artist == "Gillespie" then
"Dizzy"
elsif aSong.artist == "Parker" then
"Bird"
else
"unknown"
end
</pre></td></tr></table>
<P></P>
Ruby also has a negated form of the <code>if</code> statement:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
unless aSong.duration > 180 then
cost = .25
else
cost = .35
end
</pre></td></tr></table>
<P></P>
Finally, for the C fans out there, Ruby also supports the C-style
conditional expression:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
cost = aSong.duration > 180 ? .35 : .25
</pre></td></tr></table>
<P></P>
The conditional expression returns the value of either the expression
before or the expression after the colon, depending on whether the
boolean expression before the question mark evaluates to <code>true</code>
or <code>false</code>. In this case, if the song duration is greater than 3
minutes, the expression returns .35. For shorter songs, it returns
.25. Whatever the result, it is then assigned to <code>cost</code>.
<h3>If and Unless Modifiers</h3>
<P></P>
Ruby shares a neat feature with Perl. Statement modifiers let you tack
conditional statements onto the end of a normal statement.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
mon, day, year = $1, $2, $3 if /(\d\d)-(\d\d)-(\d\d)/
puts "a = #{a}" if fDebug
print total unless total == 0
</pre></td></tr></table>
<P></P>
For an <code>if</code> modifier, the preceding expression will be evaluated only
if the condition is true. <code>unless</code> works the other way around.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
while gets
next if /^#/ # Skip comments
parseLine unless /^$/ # Don't parse empty lines
end
</pre></td></tr></table>
<P></P>
Because <code>if</code> itself is an expression, you can get really obscure
with statements such as:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
if artist == "John Coltrane"
artist = "'Trane"
end unless nicknames == "no"
</pre></td></tr></table>
<P></P>
This path leads to the gates of madness.
<h2>Case Expressions</h2>
<P></P>
The Ruby <code>case</code> expression is a powerful beast: a multiway <code>if</code>
on steroids.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
case inputLine
<P></P>
when "debug"
dumpDebugInfo
dumpSymbols
<P></P>
when /p\s+(\w+)/
dumpVariable($1)
<P></P>
when "quit", "exit"
exit
<P></P>
else
print "Illegal command: #{inputLine}"
end
</pre></td></tr></table>
<P></P>
As with <code>if</code>, <code>case</code> returns the value of the last expression
executed, and you also need a <code>then</code> keyword if the
expression is on the same line as the condition.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
kind = case year
when 1850..1889 then "Blues"
when 1890..1909 then "Ragtime"
when 1910..1929 then "New Orleans Jazz"
when 1930..1939 then "Swing"
when 1940..1950 then "Bebop"
else "Jazz"
end
</pre></td></tr></table>
<P></P>
<code>case</code> operates by comparing the target (the expression after the
keyword <code>case</code>) with each of the comparison expressions after the
<code>when</code> keywords. This test is done using
<em>comparison</em> <code>===</code> <em>target</em>.
As long as a class defines
meaningful semantics for <code>===</code> (and all the built-in classes do),
objects of that class can be used in case expressions.
<P></P>
For example, regular expressions define <code>===</code> as a simple pattern match.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
case line
when /title=(.*)/
puts "Title is #$1"
when /track=(.*)/
puts "Track is #$1"
when /artist=(.*)/
puts "Artist is #$1"
end
</pre></td></tr></table>
<P></P>
Ruby classes are instances of class <code>Class</code>, which defines <code>===</code>
as a test to see if the argument is an instance of the class or one of
its superclasses. So (abandoning the benefits of polymorphism and
bringing the gods of refactoring down around your ears), you can test
the class of objects:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
case shape
when Square, Rectangle
# ...
when Circle
# ...
when Triangle
# ...
else
# ...
end
</pre></td></tr></table>
<h2>Loops</h2>
<P></P>
Don't tell anyone, but Ruby has pretty primitive built-in looping
constructs.
<P></P>
The <code>while</code> loop executes its body zero or more times as long as
its condition is true. For example, this common idiom reads until
the input is exhausted.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
while gets
# ...
end
</pre></td></tr></table>
<P></P>
There's also a negated form that executes the body until the
condition becomes true.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
until playList.duration > 60
playList.add(songList.pop)
end
</pre></td></tr></table>
<P></P>
As with <code>if</code> and <code>unless</code>, both of the loops can also be used
as statement modifiers.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
a *= 2 while a < 100
a -= 10 until a < 100
</pre></td></tr></table>
<P></P>
On page 80 in the section on boolean
expressions,
we said that a range can be used as a kind of flip-flop, returning true
when some event happens and then staying true until a second event occurs.
This facility is normally used within loops. In the example that
follows, we read a text file containing the first ten ordinal numbers
(``first,'' ``second,'' and so on)
but only print the lines starting with the one that matches
``third'' and ending with the one that matches ``fifth.''
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
file = File.open("ordinal")
while file.gets
print if /third/ .. /fifth/
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
third
fourth
fifth
</pre></td></tr></table>
<P></P>
The elements of a range used in a boolean expression can themselves be
expressions. These are evaluated each time the overall boolean
expression is evaluated. For example, the following code uses the fact
that the variable <code>$.</code> contains the current input line number to
display line numbers one through three and those between a match of
<code>/eig/</code> and <code>/nin/</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
file = File.open("ordinal")
while file.gets
print if ($. == 1) || /eig/ .. ($. == 3) || /nin/
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
first
second
third
eighth
ninth
</pre></td></tr></table>
<P></P>
There's one wrinkle when <code>while</code> and <code>until</code> are used as statement
modifiers. If the statement they are modifying is a
<code>begin</code>/<code>end</code> block,
the code in the block will always execute
at least one time, regardless of the value of the boolean expression.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
print "Hello\n" while false
begin
print "Goodbye\n"
end while false
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Goodbye
</pre></td></tr></table>
<h3>Iterators</h3>
<P></P>
If you read the beginning of the previous section, you might have been
discouraged. ``Ruby has pretty primitive built-in looping
constructs,'' it said. Don't despair, gentle reader, for there's good
news. Ruby doesn't need any sophisticated built-in loops, because all
the fun stuff is implemented using Ruby iterators.
<P></P>
For example, Ruby doesn't have a ``for'' loop---at least not the kind
you'd find in C, C++, and Java. Instead, Ruby uses methods defined in
various built-in classes to provide equivalent, but less error-prone,
functionality.
<P></P>
Let's look at some examples.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
3.times do
print "Ho! "
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Ho! Ho! Ho!
</pre></td></tr></table>
<P></P>
It's easy to avoid fencepost and off-by-1 errors; this loop will
execute three times, period. In addition to <code>times</code>, integers
can loop over specific ranges by calling <code>downto</code>,
<code>upto</code>, and <code>step</code>. For instance, a traditional ``for''
loop that runs from 0 to 9 (something like <code>i=0; i < 10; i++</code>)
is written as follows.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
0.upto(9) do |x|
print x, " "
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
0 1 2 3 4 5 6 7 8 9
</pre></td></tr></table>
<P></P>
A loop from 0 to 12 by 3 can be written as follows.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
0.step(12, 3) {|x| print x, " " }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
0 3 6 9 12
</pre></td></tr></table>
<P></P>
Similarly, iterating over arrays and other containers is made easy
using their <code>each</code> method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
[ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
1 1 2 3 5
</pre></td></tr></table>
<P></P>
And once a class supports <code>each</code>, the additional methods in the
<code>Enumerable</code> module (documented beginning on page 407
and summarized on pages 104--105)
become available. For example, the <code>File</code> class provides an
<code>each</code> method, which returns each line of a file in turn. Using
the <code>grep</code> method in <code>Enumerable</code>, we could iterate over only
those lines that meet a certain condition.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
File.open("ordinal").grep /d$/ do |line|
print line
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
second
third
</pre></td></tr></table>
<P></P>
Last, and probably least, is the most basic loop of all. Ruby provides
a built-in iterator called <code>loop</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
loop {
# block ...
}
</pre></td></tr></table>
<P></P>
The <code>loop</code> iterator calls the associated block forever (or at
least until you break out of the loop, but you'll have to read ahead
to find out how to do that).
<h3>For ... In</h3>
<P></P>
Earlier we said that the only built-in Ruby looping primitives were
<code>while</code> and <code>until</code>. What's this ``<code>for</code>'' thing, then?
Well, <code>for</code> is almost a lump of syntactic sugar. When you write
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
for aSong in songList
aSong.play
end
</pre></td></tr></table>
<P></P>
Ruby translates it into something like:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songList.each do |aSong|
aSong.play
end
</pre></td></tr></table>
<P></P>
The only difference between the <code>for</code> loop and the <code>each</code>
form is the scope of local variables that are defined in the body.
This is discussed on page 89.
<P></P>
You can use <code>for</code>
to iterate over any object that responds to the method <code>each</code>, such
as an <code>Array</code> or a <code>Range</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
for i in ['fee', 'fi', 'fo', 'fum']
print i, " "
end
for i in 1..3
print i, " "
end
for i in File.open("ordinal").find_all { |l| l =~ /d$/}
print i.chomp, " "
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
fee fi fo fum 1 2 3 second third
</pre></td></tr></table>
<P></P>
As long as your class defines a sensible <code>each</code> method, you can use
a <code>for</code> loop to traverse it.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Periods
def each
yield "Classical"
yield "Jazz"
yield "Rock"
end
end
<P></P>
periods = Periods.new
for genre in periods
print genre, " "
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Classical Jazz Rock
</pre></td></tr></table>
<h3>Break, Redo, and Next</h3>
<P></P>
The loop control constructs <code>break</code>, <code>redo</code>, and <code>next</code>
let you alter the normal flow through a loop or iterator.
<P></P>
<code>break</code> terminates the immediately enclosing loop; control resumes
at the statement following the block. <code>redo</code> repeats the loop from
the start, but without reevaluating the condition or fetching the
next element (in an iterator). <code>next</code> skips to the end of the
loop, effectively starting the next iteration.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
while gets
next if /^\s*#/ # skip comments
break if /^END/ # stop at end
# substitute stuff in backticks and try again
redo if gsub!(/`(.*?)`/) { eval($1) }
# process line ...
end
</pre></td></tr></table>
<P></P>
These keywords can also be used with any of the iterator-based
looping mechanisms:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
i=0
loop do
i += 1
next if i < 3
print i
break if i > 4
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
345
</pre></td></tr></table>
<h3>Retry</h3>
<P></P>
The <code>redo</code> statement causes a loop to repeat the current
iteration. Sometimes, though, you need to wind the loop right back to
the very beginning. The <code>retry</code> statement is just the
ticket. <code>retry</code> restarts any kind of iterator loop.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
for i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end
</pre></td></tr></table>
<P></P>
Running this interactively, you might see
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Now at 1. Restart? n
Now at 2. Restart? y
Now at 1. Restart? n
. . .
</pre></td></tr></table>
<P></P>
<code>retry</code> will reevaluate any arguments to the iterator before
restarting it. The online Ruby documentation has the following example
of a do-it-yourself <em>until</em> loop.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def doUntil(cond)
yield
retry unless cond
end
<P></P>
i = 0
doUntil(i > 3) {
print i, " "
i += 1
}
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
0 1 2 3 4
</pre></td></tr></table>
<h2>Variable Scope and Loops</h2>
<P></P>
The <code>while</code>, <code>until</code>, and <code>for</code> loops are built into the
language and do not introduce new scope; previously existing locals
can be used in the loop, and any new locals created will be available
afterward.
<P></P>
The blocks used by iterators (such as <code>loop</code> and <code>each</code>) are
a little different. Normally, the local variables created in these
blocks are not accessible outside the block.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
[ 1, 2, 3 ].each do |x|
y = x + 1
end
[ x, y ]
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
prog.rb:4: undefined local variable or method `x'<br>for #<Object:0x4019ac90> (NameError)
</pre></td></tr></table>
<P></P>
However, if at the time the block executes a local variable
already exists with the same name as that of a
variable in the block, the existing local variable will be used in the
block. Its value will therefore be available after the block finishes.
As the following example shows, this applies both to normal variables in the
block and to the block's parameters.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>x = nil</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>y = nil</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>[ 1, 2, 3 ].each do |x|</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> y = x + 1</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td valign="top"><code>[ x, y ]</code></td>
<td valign="top"></td>
<td valign="top"><code>[3, 4]</code></td>
</tr>
</table>
<P></P>
<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_methods.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_exceptions.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>
|