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 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
|
<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="Expressions">
<p/>
So far we've been fairly cavalier in our use of expressions in Ruby.
After all, <tt>a=b+c</tt> is pretty standard
stuff. You could write a whole heap of Ruby code without reading any
of this chapter.
<p/>
But it wouldn't be as much fun <tt>;-)</tt>.
<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/>
Some obvious things include the ability to chain statements together.
<p/>
<codefragment>
<fullcode><![CDATA[ a = b = c = 0
[ 3, 1, 7, 0 ].sort.reverse
]]></fullcode><rubycode>
<tr>
<td><tt>a<nbsp/>=<nbsp/>b<nbsp/>=<nbsp/>c<nbsp/>=<nbsp/>0</tt></td>
<td>»</td>
<td><tt>0</tt></td>
</tr>
<tr>
<td><tt>[<nbsp/>3,<nbsp/>1,<nbsp/>7,<nbsp/>0<nbsp/>].sort.reverse</tt></td>
<td>»</td>
<td><tt>[7,<nbsp/>3,<nbsp/>1,<nbsp/>0]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Perhaps less obvious, things that are normally statements in C
or Java are expressions in Ruby. For example, the <kw>if</kw> and
<kw>case</kw> statements both return the value of the last expression
executed.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class Song
!- TradJazz, Jazz, Other = 1, 2, 3
!- attr :written
!- def mp3Type() @written = 1; 1 end
!- end
!- class Date
!- def initialize(a,b,c) end
!- def coerce(i) [1,1] end
!- end
!- class Rating
!- SkipThisOne, CouldDoBetter, Rave = 1, 2, 3
!- end
!- class MP3
!- Jazz = 1
!- end
!- song = Song.new
!- votesCast = 0
songType = if song.mp3Type == MP3::Jazz
if song.written < Date.new(1935, 1, 1)
Song::TradJazz
else
Song::Jazz
end
else
Song::Other
end
rating = case votesCast
when 0...10 then Rating::SkipThisOne
when 10...50 then Rating::CouldDoBetter
else Rating::Rave
end
]]></fullcode>
songType<nbsp/>=<nbsp/>if<nbsp/>song.mp3Type<nbsp/>==<nbsp/>MP3::Jazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>song.written<nbsp/><<nbsp/>Date.new(1935,<nbsp/>1,<nbsp/>1)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::TradJazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::Jazz
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Song::Other
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/>rating<nbsp/>=<nbsp/>case<nbsp/>votesCast
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>0...10<nbsp/><nbsp/><nbsp/><nbsp/>then<nbsp/>Rating::SkipThisOne
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>10...50<nbsp/><nbsp/><nbsp/>then<nbsp/>Rating::CouldDoBetter
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>Rating::Rave
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
We'll talk more about <kw>if</kw> and <kw>case</kw> starting
on page 81.
<section>Operator Expressions</section>
<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/>
In Ruby, many operators are actually method calls. When you write
<tt>a*b+c</tt>
you're actually asking the object referenced by <var>a</var> to execute the
method ``<tt>*</tt>'', passing in the parameter <var>b</var>. You then ask the
object that results from that calculation to execute ``<tt>+</tt>'',
passing <var>c</var> as a parameter. This is exactly equivalent
to writing
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- a,b,c=1,2,3
(a.*(b)).+(c)
]]></fullcode>
(a.*(b)).+(c)
</alltt>
</codefragment>
<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/>
<codefragment>
<fullcode><![CDATA[ class Fixnum
alias oldPlus +
def +(other)
oldPlus(other).succ
end
end
1 + 2
a = 3
a += 4
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Fixnum</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>alias<nbsp/>oldPlus<nbsp/>+</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>+(other)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>oldPlus(other).succ</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><tt>1<nbsp/>+<nbsp/>2</tt></td>
<td>»</td>
<td><tt>4</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>3</tt></td>
</tr>
<tr>
<td><tt>a<nbsp/>+=<nbsp/>4</tt></td>
<td>»</td>
<td><tt>8</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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
``<tt>[]</tt>'' to specify the music to be extracted.
<p/>
<codefragment>
<alltt><fullcode><
result = Song.new(self.title + " [extract]",
self.artist,
toTime - fromTime)
result.setStartTime(fromTime)
result
end
end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>def<nbsp/>[](fromTime,<nbsp/>toTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>Song.new(self.title<nbsp/>+<nbsp/>"<nbsp/>[extract]",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>self.artist,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>toTime<nbsp/>-<nbsp/>fromTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result.setStartTime(fromTime)
<nbsp/><nbsp/><nbsp/><nbsp/>result
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This code fragment extends class <classname>Song</classname> with the method
``<tt>[]</tt>'', 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/>
<codefragment>
<alltt><fullcode><![CDATA[ aSong[0, 0.15].play
]]></fullcode>
aSong[0,<nbsp/>0.15].play
</alltt>
</codefragment>
<section>Miscellaneous Expressions</section>
<p/>
As well as the obvious operator expressions and method calls, and the
(perhaps) less obvious statement expressions (such as <kw>if</kw> and
<kw>case</kw>), Ruby has a few more things that you can use in
expressions.
<subsection>Command Expansion</subsection>
<p/>
If you enclose a string in backquotes, or use the delimited form
prefixed by <tt>%x</tt>, 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/>
<codefragment>
<fullcode><![CDATA[ `date`
`dir`.split[34]
%x{echo "Hello there"}
]]></fullcode><rubycode>
<tr>
<td><tt>`date`</tt></td>
<td>»</td>
<td><tt>"Sun<nbsp/>Mar<nbsp/><nbsp/>4<nbsp/>23:23:52<nbsp/>CST<nbsp/>2001\n"</tt></td>
</tr>
<tr>
<td><tt>`dir`.split[34]</tt></td>
<td>»</td>
<td><tt>"lib_pstore.txi"</tt></td>
</tr>
<tr>
<td><tt>%x{echo<nbsp/>"Hello<nbsp/>there"}</tt></td>
<td>»</td>
<td><tt>"Hello<nbsp/>there\n"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can use expression expansion and all the usual escape sequences in
the command string.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ for i in 0..3
status = `dbmanager status id=#{i}`
# ...
end
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>0..3
<nbsp/><nbsp/>status<nbsp/>=<nbsp/>`dbmanager<nbsp/>status<nbsp/>id=#{i}`
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
The exit status of the command is available in the global variable
<var>$?</var>.
<subsubsection>Backquotes Are Soft</subsubsection>
<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 <mmm><file>kernel</file><front>Kernel</front><back>`</back><mref>_bq</mref></mmm>
(a single backquote). If you want, you can override
this.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ alias oldBackquote `
def `(cmd)
result = oldBackquote(cmd)
if $? != 0
raise "Command #{cmd} failed"
end
result
end
print `date`
print `data`
]]></fullcode>
alias<nbsp/>oldBackquote<nbsp/>`
def<nbsp/>`(cmd)
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>oldBackquote(cmd)
<nbsp/><nbsp/>if<nbsp/>$?<nbsp/>!=<nbsp/>0
<nbsp/><nbsp/><nbsp/><nbsp/>raise<nbsp/>"Command<nbsp/>#{cmd}<nbsp/>failed"
<nbsp/><nbsp/>end
<nbsp/><nbsp/>result
end
print<nbsp/>`date`
print<nbsp/>`data`
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Sun<nbsp/>Mar<nbsp/><nbsp/>4<nbsp/>23:23:52<nbsp/>CST<nbsp/>2001
prog.rb:3:<nbsp/>command<nbsp/>not<nbsp/>found:<nbsp/>data
prog.rb:5:in<nbsp/>``':<nbsp/>Command<nbsp/>data<nbsp/>failed<nbsp/>(RuntimeError)
from<nbsp/>prog.rb:10
</alltt>
</codefragment>
<section>Assignment</section>
<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/>
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/>
<codefragment>
<fullcode><![CDATA[!-$stdin = DATA
a = b = 1 + 2 + 3
a
b
a = (b = 1 + 2) + 3
a
b
File.open(name = gets.chomp)
!-__END__
!-testfile
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>b<nbsp/>=<nbsp/>1<nbsp/>+<nbsp/>2<nbsp/>+<nbsp/>3</tt></td>
</tr>
<tr>
<td><tt>a</tt></td>
<td>»</td>
<td><tt>6</tt></td>
</tr>
<tr>
<td><tt>b</tt></td>
<td>»</td>
<td><tt>6</tt></td>
</tr>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>(b<nbsp/>=<nbsp/>1<nbsp/>+<nbsp/>2)<nbsp/>+<nbsp/>3</tt></td>
</tr>
<tr>
<td><tt>a</tt></td>
<td>»</td>
<td><tt>6</tt></td>
</tr>
<tr>
<td><tt>b</tt></td>
<td>»</td>
<td><tt>3</tt></td>
</tr>
<tr>
<td colspan="3"><tt>File.open(name<nbsp/>=<nbsp/>gets.chomp)</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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/>
<codefragment>
<alltt><fullcode><![CDATA[ instrument = "piano"
MIDDLE_A = 440
]]></fullcode>
instrument<nbsp/>=<nbsp/>"piano"
MIDDLE_A<nbsp/><nbsp/><nbsp/>=<nbsp/>440
</alltt>
</codefragment>
<p/>
The second form of assignment involves having an object attribute or
element reference on the left-hand side.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Song
!- include Comparable
!- @@plays = 0
!- attr_reader :name, :artist, :duration
!- attr_writer :duration
!- def initialize(name, artist, duration)
!- @name = name
!- @artist = artist
!- @duration = duration
!- @plays = 0
!- end
!- def to_s
!- "Song: #{@name}--#{@artist} (#{@duration})"
!- end
!- def name
!- @name
!- end
!- def artist
!- @artist
!- end
!- def duration
!- @duration
!- end
!- def duration=(newDuration)
!- @duration = newDuration
!- end
!- def durationInMinutes
!- @duration/60.0 # force floating point
!- end
!- def durationInMinutes=(value)
!- @duration = (value*60).to_i
!- end
!- def play
!- @plays += 1
!- @@plays += 1
!- "This song: #@plays plays. Total #@@plays plays."
!- end
!- def record
!- "Recording..."
!- end
!- def inspect
!- self.to_s
!- end
!- def <=>(other)
!- self.duration <=> other.duration
!- end
!-end
!-instrument = "piano"
!-aSong = Song.new(1,2,3)
aSong.duration = 234
instrument["ano"] = "ccolo"
]]></fullcode>
aSong.duration<nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>234
instrument["ano"]<nbsp/>=<nbsp/>"ccolo"
</alltt>
</codefragment>
<p/>
These forms are special, because they are implemented by calling
methods in the lvalues, which means you can override them.
<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/>
<codefragment>
<alltt><fullcode><![CDATA[class Song
!- include Comparable
!- @@plays = 0
!- attr_reader :name, :artist, :duration
!- attr_writer :duration
!- def initialize(name, artist, duration)
!- @name = name
!- @artist = artist
!- @duration = duration
!- @plays = 0
!- end
!- def to_s
!- "Song: #{@name}--#{@artist} (#{@duration})"
!- end
!- def name
!- @name
!- end
!- def artist
!- @artist
!- end
!- def duration
!- @duration
!- end
def duration=(newDuration)
@duration = newDuration
end
!- def durationInMinutes
!- @duration/60.0 # force floating point
!- end
!- def durationInMinutes=(value)
!- @duration = (value*60).to_i
!- end
!- def play
!- @plays += 1
!- @@plays += 1
!- "This song: #@plays plays. Total #@@plays plays."
!- end
!- def record
!- "Recording..."
!- end
!- def inspect
!- self.to_s
!- end
!- def <=>(other)
!- self.duration <=> other.duration
!- end
end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>def<nbsp/>duration=(newDuration)
<nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>newDuration
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<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/>
<codefragment>
<alltt><fullcode><![CDATA[ class Amplifier
def volume=(newVolume)
self.leftChannel = self.rightChannel = newVolume
end
# ...
end
]]></fullcode>
class<nbsp/>Amplifier
<nbsp/><nbsp/>def<nbsp/>volume=(newVolume)
<nbsp/><nbsp/><nbsp/><nbsp/>self.leftChannel<nbsp/>=<nbsp/>self.rightChannel<nbsp/>=<nbsp/>newVolume
<nbsp/><nbsp/>end
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
<sidebar name="Using Accessors Within a Class">
<p/>
Why did we write <tt>self.leftChannel</tt> 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 <tt>self</tt>). 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.
<codefragment>
<fullcode><![CDATA[ class BrokenAmplifier
attr_accessor :leftChannel, :rightChannel
def volume=(vol)
leftChannel = self.rightChannel = vol
end
end
ba = BrokenAmplifier.new
ba.leftChannel = ba.rightChannel = 99
ba.volume = 5
ba.leftChannel
ba.rightChannel
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>BrokenAmplifier</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>attr_accessor<nbsp/>:leftChannel,<nbsp/>:rightChannel</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>volume=(vol)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>leftChannel<nbsp/>=<nbsp/>self.rightChannel<nbsp/>=<nbsp/>vol</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>ba<nbsp/>=<nbsp/>BrokenAmplifier.new</tt></td>
</tr>
<tr>
<td colspan="3"><tt>ba.leftChannel<nbsp/>=<nbsp/>ba.rightChannel<nbsp/>=<nbsp/>99</tt></td>
</tr>
<tr>
<td colspan="3"><tt>ba.volume<nbsp/>=<nbsp/>5</tt></td>
</tr>
<tr>
<td><tt>ba.leftChannel</tt></td>
<td>»</td>
<td><tt>99</tt></td>
</tr>
<tr>
<td><tt>ba.rightChannel</tt></td>
<td>»</td>
<td><tt>5</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
We forgot to put ``<tt>self.</tt>'' in front of the assignment to
<tt>leftChannel</tt>, so Ruby stored the new value in a local variable of
method <meth>volume=</meth>; the object's attribute never got updated.
This can be a tricky bug to track down.
<p/>
</sidebar>
<subsection>Parallel Assignment</subsection>
<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/>
<codefragment>
<alltt><fullcode><![CDATA[int a = 1;
int b = 2;
int temp;
temp = a;
a = b;
b = temp;
]]></fullcode>
int<nbsp/>a<nbsp/>=<nbsp/>1;
int<nbsp/>b<nbsp/>=<nbsp/>2;
int<nbsp/>temp;
<p/>
temp<nbsp/>=<nbsp/>a;
a<nbsp/>=<nbsp/>b;
b<nbsp/>=<nbsp/>temp;
</alltt>
</codefragment>
<p/>
You can do this much more cleanly in Ruby:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- a, b = 1, 2
a, b = b, a
]]></fullcode>
a,<nbsp/>b<nbsp/>=<nbsp/>b,<nbsp/>a
</alltt>
</codefragment>
<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 <tt>a</tt>, <tt>b</tt>, and <tt>c</tt> the values of the expressions
<tt>x</tt>, <tt>x+=1</tt>, and <tt>x+=1</tt>, respectively.
<p/>
<codefragment>
<fullcode><![CDATA[ x = 0
a, b, c = x, (x += 1), (x += 1)
]]></fullcode><rubycode>
<tr>
<td><tt>x<nbsp/>=<nbsp/>0</tt></td>
<td>»</td>
<td><tt>0</tt></td>
</tr>
<tr>
<td><tt>a,<nbsp/>b,<nbsp/>c<nbsp/><nbsp/><nbsp/>=<nbsp/><nbsp/><nbsp/>x,<nbsp/>(x<nbsp/>+=<nbsp/>1),<nbsp/>(x<nbsp/>+=<nbsp/>1)</tt></td>
<td>»</td>
<td><tt>[0,<nbsp/>1,<nbsp/>2]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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 <tt>nil</tt>. 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/>
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/>
<codefragment>
<table>
<tr>
<td colspan="4"><tt>a = [1, 2, 3, 4]</tt></td>
</tr>
<tr>
<td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>a</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2</td>
</tr>
<tr>
<td>b,<nbsp/>*c<nbsp/>=<nbsp/>a</td>
<td> »</td>
<td>b == 1,</td>
<td>c == [2, 3, 4]</td>
</tr>
<tr>
<td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>99,<nbsp/><nbsp/>a</td>
<td> »</td>
<td>b == 99,</td>
<td>c == [1, 2, 3, 4]</td>
</tr>
<tr>
<td>b,<nbsp/>*c<nbsp/>=<nbsp/>99,<nbsp/><nbsp/>a</td>
<td> »</td>
<td>b == 99,</td>
<td>c == [[1, 2, 3, 4]]</td>
</tr>
<tr>
<td>b,<nbsp/><nbsp/>c<nbsp/>=<nbsp/>99,<nbsp/>*a</td>
<td> »</td>
<td>b == 99,</td>
<td>c == 1</td>
</tr>
<tr>
<td>b,<nbsp/>*c<nbsp/>=<nbsp/>99,<nbsp/>*a</td>
<td> »</td>
<td>b == 99,</td>
<td>c == [1, 2, 3, 4]</td>
</tr>
</table>
<p/>
</codefragment>
<subsubsection>Nested Assignments</subsubsection>
<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/>
<codefragment>
<table>
<tr>
<td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,2,3,4</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2,</td>
<td>d == nil,</td>
<td>e == 3</td>
</tr>
<tr>
<td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>[1,2,3,4]</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2,</td>
<td>d == nil,</td>
<td>e == 3</td>
</tr>
<tr>
<td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3],4</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2,</td>
<td>d == 3,</td>
<td>e == 4</td>
</tr>
<tr>
<td>b,<nbsp/>(c,<nbsp/>d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3,4],5</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2,</td>
<td>d == 3,</td>
<td>e == 5</td>
</tr>
<tr>
<td>b,<nbsp/>(c,*d),<nbsp/>e<nbsp/>=<nbsp/>1,[2,3,4],5</td>
<td> »</td>
<td>b == 1,</td>
<td>c == 2,</td>
<td>d == [3, 4],</td>
<td>e == 5</td>
</tr>
</table>
<p/>
</codefragment>
<subsection>Other Forms of Assignment</subsection>
<p/>
In common with many other languages, Ruby has a syntactic shortcut:
<tt>a=a+2</tt> may be written as <tt>a+=2</tt>.
<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/>
<codefragment>
<fullcode><![CDATA[ class Bowdlerize
def initialize(aString)
@value = aString.gsub(/[aeiou]/, '*')
end
def +(other)
Bowdlerize.new(self.to_s + other.to_s)
end
def to_s
@value
end
!- def inspect
!- @value
!- end
end
a = Bowdlerize.new("damn ")
a += "shame"
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Bowdlerize</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>initialize(aString)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@value<nbsp/>=<nbsp/>aString.gsub(/[aeiou]/,<nbsp/>'*')</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>+(other)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>Bowdlerize.new(self.to_s<nbsp/>+<nbsp/>other.to_s)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@value</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><tt>a<nbsp/>=<nbsp/>Bowdlerize.new("damn<nbsp/>")</tt></td>
<td>»</td>
<td><tt>d*mn</tt></td>
</tr>
<tr>
<td><tt>a<nbsp/>+=<nbsp/>"shame"</tt></td>
<td>»</td>
<td><tt>d*mn<nbsp/>sh*m*</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<section>Conditional Execution</section>
<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.
<subsection>Boolean Expressions</subsection>
<p/>
Ruby has a simple definition of truth. Any value that is not <tt>nil</tt> or
the constant <const>false</const> is true. You'll find that the library
routines use this fact consistently. For example, <cim><file>io</file><front>IO</front><back>gets</back><mref>gets</mref></cim>,
which returns the next line from a file, returns <tt>nil</tt> at end of
file, enabling you to write loops such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ while line = gets
# process line
end
]]></fullcode>
while<nbsp/>line<nbsp/>=<nbsp/>gets
<nbsp/><nbsp/>#<nbsp/>process<nbsp/>line
end
</alltt>
</codefragment>
<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.
<subsubsection>Defined?, And, Or, and Not</subsubsection>
<p/>
Ruby supports all the standard boolean operators and introduces the
new operator <tt>defined?</tt>.
<p/>
Both ``<tt>and</tt>'' and ``<tt>&&</tt>''
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 (``<tt>and</tt>'' binds lower than
``<tt>&&</tt>'').
<p/>
Similarly, both ``<tt>or</tt>'' and ``<tt>||</tt>''
evaluate to true if either operand
is true. They evaluate their second operand only if the first is
false. As with ``<tt>and</tt>'', the only difference between ``<tt>or</tt>'' and
``<tt>||</tt>'' is their precedence.
<p/>
Just to make life interesting, ``<tt>and</tt>'' and ``<tt>or</tt>'' have the
same precedence, while ``<tt>&&</tt>'' has a higher precedence than
``<tt>||</tt>''.
<p/>
``<tt>not</tt>'' and ``<tt>!</tt>''
return the opposite of their operand (false if the
operand is true, and true if the operand is false). And, yes, ``<tt>not</tt>''
and ``<tt>!</tt>'' differ only in precedence.
<p/>
All these precedence rules are summarized in Table
18.4 on page 221.
<p/>
The <tt>defined?</tt>
operator returns <tt>nil</tt> if its argument (which can be
an arbitrary expression) is not defined, otherwise it returns a
description of that argument. If the argument is <kw>yield</kw>,
<tt>defined?</tt> returns the string ``yield'' if a code block is
associated with the current context.
<p/>
<codefragment>
<fullcode><![CDATA[ defined? 1
defined? dummy
defined? printf
defined? String
defined? $&
defined? $_
defined? Math::PI
defined? ( c,d = 1,2 )
defined? 42.abs
]]></fullcode><rubycode>
<tr>
<td><tt>defined?<nbsp/>1</tt></td>
<td>»</td>
<td><tt>"expression"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>dummy</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>printf</tt></td>
<td>»</td>
<td><tt>"method"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>String</tt></td>
<td>»</td>
<td><tt>"constant"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>$&</tt></td>
<td>»</td>
<td><tt>"$&"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>$_</tt></td>
<td>»</td>
<td><tt>"global-variable"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>Math::PI</tt></td>
<td>»</td>
<td><tt>"constant"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>(<nbsp/>c,d<nbsp/>=<nbsp/>1,2<nbsp/>)</tt></td>
<td>»</td>
<td><tt>"assignment"</tt></td>
</tr>
<tr>
<td><tt>defined?<nbsp/>42.abs</tt></td>
<td>»</td>
<td><tt>"method"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
In addition to the boolean operators, Ruby objects support comparison
using the methods <tt>==</tt>, <tt>===</tt>, <tt><=></tt>, <tt>=~</tt>, <tt>eql?</tt>,
and <tt>equal?</tt> (see Table 7.1 on page 81). All but <tt><=></tt>
are defined in class <classname>Object</classname> but are often overridden by
descendents to provide appropriate semantics. For example, class
<classname>Array</classname> redefines <tt>==</tt> so that two array objects are equal if
they have the same number of elements and corresponding elements are
equal.
<p/>
<figure type="table">
<caption>Common comparison operators</caption>
<table>
<th>
<td><b>Operator</b></td>
<td><b>Meaning</b></td>
</th>
<tr>
<td><tt>==</tt></td>
<td>Test for equal value.</td>
</tr>
<tr>
<td><tt>===</tt></td>
<td>Used to test equality within a <kw>when</kw> clause of a
<kw>case</kw> statement.</td>
</tr>
<tr>
<td><tt><=></tt></td>
<td>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><tt><</tt>, <tt><=</tt>, <tt>>=</tt>, <tt>></tt></td>
<td>Comparison operators for less than, less than or
equal, greater than or equal, and greater than.</td>
</tr>
<tr>
<td><tt>=~</tt></td>
<td>Regular expression pattern match.</td>
</tr>
<tr>
<td><tt>eql?</tt></td>
<td>True if the receiver and argument have both the same
type and equal values. 1 == 1.0 returns <const>true</const>,
but 1.eql?(1.0) is <const>false</const>.</td>
</tr>
<tr>
<td><tt>equal?</tt></td>
<td>True if the receiver and argument have the same
object id.</td>
</tr>
<bottomrule/></table>
<p/>
</figure>
<p/>
Both <tt>==</tt> and <tt>=~</tt> have negated forms, <tt>!=</tt> and <tt>!~</tt>.
However, these are converted by Ruby when your program is read.
<tt>a!=b</tt> is equivalent to <tt>!(a==b)</tt>,
and <tt>a!~b</tt> is the
same as <tt>!(a=~b)</tt>. This means that if you write a class that
overrides <tt>==</tt> or <tt>=~</tt> you get a working <tt>!=</tt> and <tt>!~</tt>
for free. But on the flip side, this also means that you cannot define
<tt>!=</tt> and <tt>!~</tt> independent of <tt>==</tt> and <tt>=~</tt>, respectively.
<p/>
You can use a Ruby range as a boolean expression.
A
range such as <tt>exp1..exp2</tt> will evaluate as false
until <tt>exp1</tt> becomes true. The range will then evaluate as true
until <tt>exp2</tt> becomes true. Once this happens, the range resets,
ready to fire again. We show some examples of this
on page 84.
<p/>
Finally, you can use a bare regular expression as a boolean
expression. Ruby expands it to <tt>$_=~/re/</tt>.
<subsection>If and Unless Expressions</subsection>
<p/>
An <kw>if</kw> expression in Ruby is pretty similar to ``if'' statements
in other languages.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie" then
handle = "Dizzy"
elsif aSong.artist == "Parker" then
handle = "Bird"
else
handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
If you lay out your <kw>if</kw> statements on multiple lines, you can
leave off the <kw>then</kw> keyword.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie"
handle = "Dizzy"
elsif aSong.artist == "Parker"
handle = "Bird"
else
handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else
<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
However, if you lay your code out more tightly, the <kw>then</kw> keyword
is necessary to separate the boolean expression from the following
statements.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
if aSong.artist == "Gillespie" then handle = "Dizzy"
elsif aSong.artist == "Parker" then handle = "Bird"
else handle = "unknown"
end
]]></fullcode>
if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Dizzy"
elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"Bird"
else<nbsp/><nbsp/>handle<nbsp/>=<nbsp/>"unknown"
end
</alltt>
</codefragment>
<p/>
You can have zero or more <tt>elsif</tt> clauses and an optional
<tt>else</tt> clause.
<p/>
As we've said before, <tt>if</tt> is
an expression, not a statement---it returns a value. You don't have
to use the value of an <tt>if</tt> expression, but it can come in handy.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.artist() nil end
handle = if aSong.artist == "Gillespie" then
"Dizzy"
elsif aSong.artist == "Parker" then
"Bird"
else
"unknown"
end
]]></fullcode>
handle<nbsp/>=<nbsp/>if<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Gillespie"<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Dizzy"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>elsif<nbsp/>aSong.artist<nbsp/>==<nbsp/>"Parker"<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Bird"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"unknown"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
Ruby also has a negated form of the <tt>if</tt> statement:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.duration() 1 end
unless aSong.duration > 180 then
cost = .25
else
cost = .35
end
]]></fullcode>
unless<nbsp/>aSong.duration<nbsp/>><nbsp/>180<nbsp/>then
<nbsp/><nbsp/>cost<nbsp/>=<nbsp/>.25
else
<nbsp/><nbsp/>cost<nbsp/>=<nbsp/>.35
end
</alltt>
</codefragment>
<p/>
Finally, for the C fans out there, Ruby also supports the C-style
conditional expression:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aSong = ""
!-def aSong.duration() 1 end
cost = aSong.duration > 180 ? .35 : .25
]]></fullcode>
cost<nbsp/>=<nbsp/>aSong.duration<nbsp/>><nbsp/>180<nbsp/>?<nbsp/>.35<nbsp/>:<nbsp/>.25
</alltt>
</codefragment>
<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 <const>true</const>
or <const>false</const>. 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 <var>cost</var>.
<subsubsection>If and Unless Modifiers</subsubsection>
<p/>
Ruby shares a neat feature with Perl. Statement modifiers let you tack
conditional statements onto the end of a normal statement.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-fDebug = false; total = 0
mon, day, year = $1, $2, $3 if /(\d\d)-(\d\d)-(\d\d)/
puts "a = #{a}" if fDebug
print total unless total == 0
]]></fullcode>
mon,<nbsp/>day,<nbsp/>year<nbsp/>=<nbsp/>$1,<nbsp/>$2,<nbsp/>$3<nbsp/>if<nbsp/>/(\d\d)-(\d\d)-(\d\d)/
puts<nbsp/>"a<nbsp/>=<nbsp/>#{a}"<nbsp/>if<nbsp/>fDebug
print<nbsp/>total<nbsp/>unless<nbsp/>total<nbsp/>==<nbsp/>0
</alltt>
</codefragment>
<p/>
For an <kw>if</kw> modifier, the preceding expression will be evaluated only
if the condition is true. <kw>unless</kw> works the other way around.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ while gets
next if /^#/ # Skip comments
parseLine unless /^$/ # Don't parse empty lines
end
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>/^#/<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>Skip<nbsp/>comments
<nbsp/><nbsp/>parseLine<nbsp/>unless<nbsp/>/^$/<nbsp/><nbsp/><nbsp/>#<nbsp/>Don't<nbsp/>parse<nbsp/>empty<nbsp/>lines
end
</alltt>
</codefragment>
<p/>
Because <kw>if</kw> itself is an expression, you can get really obscure
with statements such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- artist = "John Coltrane"
!- nicknames = "yes"
if artist == "John Coltrane"
artist = "'Trane"
end unless nicknames == "no"
]]></fullcode>
if<nbsp/>artist<nbsp/>==<nbsp/>"John<nbsp/>Coltrane"
<nbsp/><nbsp/>artist<nbsp/>=<nbsp/>"'Trane"
end<nbsp/>unless<nbsp/>nicknames<nbsp/>==<nbsp/>"no"
</alltt>
</codefragment>
<p/>
This path leads to the gates of madness.
<section>Case Expressions</section>
<p/>
The Ruby <tt>case</tt> expression is a powerful beast: a multiway <tt>if</tt>
on steroids.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-inputLine = "quit"
case inputLine
when "debug"
dumpDebugInfo
dumpSymbols
when /p\s+(\w+)/
dumpVariable($1)
when "quit", "exit"
exit
else
print "Illegal command: #{inputLine}"
end
]]></fullcode>
case<nbsp/>inputLine
<p/>
<nbsp/><nbsp/>when<nbsp/>"debug"
<nbsp/><nbsp/><nbsp/><nbsp/>dumpDebugInfo
<nbsp/><nbsp/><nbsp/><nbsp/>dumpSymbols
<p/>
<nbsp/><nbsp/>when<nbsp/>/p\s+(\w+)/
<nbsp/><nbsp/><nbsp/><nbsp/>dumpVariable($1)
<p/>
<nbsp/><nbsp/>when<nbsp/>"quit",<nbsp/>"exit"
<nbsp/><nbsp/><nbsp/><nbsp/>exit
<p/>
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>print<nbsp/>"Illegal<nbsp/>command:<nbsp/>#{inputLine}"
end
</alltt>
</codefragment>
<p/>
As with <tt>if</tt>, <kw>case</kw> returns the value of the last expression
executed, and you also need a <kw>then</kw> keyword if the
expression is on the same line as the condition.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- year = 1937
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
]]></fullcode>
kind<nbsp/>=<nbsp/>case<nbsp/>year
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1850..1889<nbsp/>then<nbsp/>"Blues"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1890..1909<nbsp/>then<nbsp/>"Ragtime"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1910..1929<nbsp/>then<nbsp/>"New<nbsp/>Orleans<nbsp/>Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1930..1939<nbsp/>then<nbsp/>"Swing"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>1940..1950<nbsp/>then<nbsp/>"Bebop"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
</alltt>
</codefragment>
<p/>
<tt>case</tt> operates by comparing the target (the expression after the
keyword <kw>case</kw>) with each of the comparison expressions after the
<kw>when</kw> keywords. This test is done using
<em>comparison</em><nbsp/><tt>===</tt><nbsp/><em>target</em>.
As long as a class defines
meaningful semantics for <tt>===</tt> (and all the built-in classes do),
objects of that class can be used in case expressions.
<p/>
For example, regular expressions define <tt>===</tt> as a simple pattern match.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ case line
when /title=(.*)/
puts "Title is #$1"
when /track=(.*)/
puts "Track is #$1"
when /artist=(.*)/
puts "Artist is #$1"
end
]]></fullcode>
case<nbsp/>line
<nbsp/><nbsp/>when<nbsp/>/title=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Title<nbsp/>is<nbsp/>#$1"
<nbsp/><nbsp/>when<nbsp/>/track=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Track<nbsp/>is<nbsp/>#$1"
<nbsp/><nbsp/>when<nbsp/>/artist=(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"Artist<nbsp/>is<nbsp/>#$1"
end
</alltt>
</codefragment>
<p/>
Ruby classes are instances of class <classname>Class</classname>, which defines <tt>===</tt>
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/>
<codefragment>
<alltt><fullcode><![CDATA[!- class Square; end
!- class Rectangle; end
!- class Circle; end
!- class Triangle; end
!- shape = Object.new
case shape
when Square, Rectangle
# ...
when Circle
# ...
when Triangle
# ...
else
# ...
end
]]></fullcode>
case<nbsp/>shape
<nbsp/><nbsp/>when<nbsp/>Square,<nbsp/>Rectangle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>when<nbsp/>Circle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>when<nbsp/>Triangle
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<section>Loops</section>
<p/>
Don't tell anyone, but Ruby has pretty primitive built-in looping
constructs.
<p/>
The <kw>while</kw> 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/>
<codefragment>
<alltt><fullcode><![CDATA[ while gets
# ...
end
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>#<nbsp/>...
end
</alltt>
</codefragment>
<p/>
There's also a negated form that executes the body until the
condition becomes true.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-playList = ""
!-def playList.duration() 100 end
until playList.duration > 60
playList.add(songList.pop)
end
]]></fullcode>
until<nbsp/>playList.duration<nbsp/>><nbsp/>60
<nbsp/><nbsp/>playList.add(songList.pop)
end
</alltt>
</codefragment>
<p/>
As with <kw>if</kw> and <kw>unless</kw>, both of the loops can also be used
as statement modifiers.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- a = 1
a *= 2 while a < 100
a -= 10 until a < 100
]]></fullcode>
a<nbsp/>*=<nbsp/>2<nbsp/>while<nbsp/>a<nbsp/><<nbsp/>100
a<nbsp/>-=<nbsp/>10<nbsp/>until<nbsp/>a<nbsp/><<nbsp/>100
</alltt>
</codefragment>
<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/>
<codefragment>
<alltt><fullcode><![CDATA[ file = File.open("ordinal")
while file.gets
print if /third/ .. /fifth/
end
]]></fullcode>
file<nbsp/>=<nbsp/>File.open("ordinal")
while<nbsp/>file.gets
<nbsp/><nbsp/>print<nbsp/><nbsp/>if<nbsp/>/third/<nbsp/>..<nbsp/>/fifth/
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
third
fourth
fifth
</alltt>
</codefragment>
<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 <var>$.</var> contains the current input line number to
display line numbers one through three and those between a match of
<tt>/eig/</tt> and <tt>/nin/</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ file = File.open("ordinal")
while file.gets
print if ($. == 1) || /eig/ .. ($. == 3) || /nin/
end
]]></fullcode>
file<nbsp/>=<nbsp/>File.open("ordinal")
while<nbsp/>file.gets
<nbsp/><nbsp/>print<nbsp/>if<nbsp/>($.<nbsp/>==<nbsp/>1)<nbsp/>||<nbsp/>/eig/<nbsp/>..<nbsp/>($.<nbsp/>==<nbsp/>3)<nbsp/>||<nbsp/>/nin/
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
first
second
third
eighth
ninth
</alltt>
</codefragment>
<p/>
There's one wrinkle when <kw>while</kw> and <kw>until</kw> are used as statement
modifiers. If the statement they are modifying is a
<kw>begin</kw>/<kw>end</kw> block,
the code in the block will always execute
at least one time, regardless of the value of the boolean expression.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ print "Hello\n" while false
begin
print "Goodbye\n"
end while false
]]></fullcode>
print<nbsp/>"Hello\n"<nbsp/>while<nbsp/>false
begin
<nbsp/><nbsp/>print<nbsp/>"Goodbye\n"
end<nbsp/>while<nbsp/>false
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Goodbye
</alltt>
</codefragment>
<subsection>Iterators</subsection>
<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/>
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/>
Let's look at some examples.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ 3.times do
print "Ho! "
end
!- puts
]]></fullcode>
3.times<nbsp/>do
<nbsp/><nbsp/>print<nbsp/>"Ho!<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Ho!<nbsp/>Ho!<nbsp/>Ho!
</alltt>
</codefragment>
<p/>
It's easy to avoid fencepost and off-by-1 errors; this loop will
execute three times, period. In addition to <meth>times</meth>, integers
can loop over specific ranges by calling <meth>downto</meth>,
<meth>upto</meth>, and <meth>step</meth>. For instance, a traditional ``for''
loop that runs from 0 to 9 (something like <tt>i=0; i < 10; i++</tt>)
is written as follows.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ 0.upto(9) do |x|
print x, " "
end
!- puts
]]></fullcode>
0.upto(9)<nbsp/>do<nbsp/>|x|
<nbsp/><nbsp/>print<nbsp/>x,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>4<nbsp/>5<nbsp/>6<nbsp/>7<nbsp/>8<nbsp/>9
</alltt>
</codefragment>
<p/>
A loop from 0 to 12 by 3 can be written as follows.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ 0.step(12, 3) {|x| print x, " " }
!- puts
]]></fullcode>
0.step(12,<nbsp/>3)<nbsp/>{|x|<nbsp/>print<nbsp/>x,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>3<nbsp/>6<nbsp/>9<nbsp/>12
</alltt>
</codefragment>
<p/>
Similarly, iterating over arrays and other containers is made easy
using their <meth>each</meth> method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ [ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
!- puts
]]></fullcode>
[<nbsp/>1,<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>5<nbsp/>].each<nbsp/>{|val|<nbsp/>print<nbsp/>val,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>5
</alltt>
</codefragment>
<p/>
And once a class supports <meth>each</meth>, the additional methods in the
<modulename>Enumerable</modulename> module (documented beginning on page 407
and summarized on pages 104--105)
become available. For example, the <classname>File</classname> class provides an
<meth>each</meth> method, which returns each line of a file in turn. Using
the <meth>grep</meth> method in <modulename>Enumerable</modulename>, we could iterate over only
those lines that meet a certain condition.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ File.open("ordinal").grep /d$/ do |line|
print line
end
]]></fullcode>
File.open("ordinal").grep<nbsp/>/d$/<nbsp/>do<nbsp/>|line|
<nbsp/><nbsp/>print<nbsp/>line
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
second
third
</alltt>
</codefragment>
<p/>
Last, and probably least, is the most basic loop of all. Ruby provides
a built-in iterator called <meth>loop</meth>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[loop {
# block ...
}
]]></fullcode>
loop<nbsp/>{
<nbsp/><nbsp/>#<nbsp/>block<nbsp/>...
}
</alltt>
</codefragment>
<p/>
The <meth>loop</meth> 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).
<subsection>For ... In</subsection>
<p/>
Earlier we said that the only built-in Ruby looping primitives were
<kw>while</kw> and <kw>until</kw>. What's this ``<kw>for</kw>'' thing, then?
Well, <kw>for</kw> is almost a lump of syntactic sugar. When you write
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-songList = ""
!-def songList.each() end
for aSong in songList
aSong.play
end
]]></fullcode>
for<nbsp/>aSong<nbsp/>in<nbsp/>songList
<nbsp/><nbsp/>aSong.play
end
</alltt>
</codefragment>
<p/>
Ruby translates it into something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-songList = ""
!-def songList.each() end
songList.each do |aSong|
aSong.play
end
]]></fullcode>
songList.each<nbsp/>do<nbsp/>|aSong|
<nbsp/><nbsp/>aSong.play
end
</alltt>
</codefragment>
<p/>
The only difference between the <kw>for</kw> loop and the <meth>each</meth>
form is the scope of local variables that are defined in the body.
This is discussed on page 89.
<p/>
You can use <kw>for</kw>
to iterate over any object that responds to the method <tt>each</tt>, such
as an <classname>Array</classname> or a <classname>Range</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ 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
!-puts
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>['fee',<nbsp/>'fi',<nbsp/>'fo',<nbsp/>'fum']
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
end
for<nbsp/>i<nbsp/>in<nbsp/>1..3
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
end
for<nbsp/>i<nbsp/>in<nbsp/>File.open("ordinal").find_all<nbsp/>{<nbsp/>|l|<nbsp/>l<nbsp/>=~<nbsp/>/d$/}
<nbsp/><nbsp/>print<nbsp/>i.chomp,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
fee<nbsp/>fi<nbsp/>fo<nbsp/>fum<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>second<nbsp/>third
</alltt>
</codefragment>
<p/>
As long as your class defines a sensible <tt>each</tt> method, you can use
a <tt>for</tt> loop to traverse it.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ class Periods
def each
yield "Classical"
yield "Jazz"
yield "Rock"
end
end
periods = Periods.new
for genre in periods
print genre, " "
end
!-puts
]]></fullcode>
class<nbsp/>Periods
<nbsp/><nbsp/>def<nbsp/>each
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Classical"
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Jazz"
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>"Rock"
<nbsp/><nbsp/>end
end
<p/>
periods<nbsp/>=<nbsp/>Periods.new
for<nbsp/>genre<nbsp/>in<nbsp/>periods
<nbsp/><nbsp/>print<nbsp/>genre,<nbsp/>"<nbsp/>"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Classical<nbsp/>Jazz<nbsp/>Rock
</alltt>
</codefragment>
<subsection>Break, Redo, and Next</subsection>
<p/>
The loop control constructs <kw>break</kw>, <kw>redo</kw>, and <kw>next</kw>
let you alter the normal flow through a loop or iterator.
<p/>
<kw>break</kw> terminates the immediately enclosing loop; control resumes
at the statement following the block. <kw>redo</kw> repeats the loop from
the start, but without reevaluating the condition or fetching the
next element (in an iterator). <kw>next</kw> skips to the end of the
loop, effectively starting the next iteration.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ 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
]]></fullcode>
while<nbsp/>gets
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>/^\s*#/<nbsp/><nbsp/><nbsp/>#<nbsp/>skip<nbsp/>comments
<nbsp/><nbsp/>break<nbsp/>if<nbsp/>/^END/<nbsp/><nbsp/><nbsp/>#<nbsp/>stop<nbsp/>at<nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>substitute<nbsp/>stuff<nbsp/>in<nbsp/>backticks<nbsp/>and<nbsp/>try<nbsp/>again
<nbsp/><nbsp/>redo<nbsp/>if<nbsp/>gsub!(/`(.*?)`/)<nbsp/>{<nbsp/>eval($1)<nbsp/>}
<nbsp/><nbsp/>#<nbsp/>process<nbsp/>line<nbsp/>...
end
</alltt>
</codefragment>
<p/>
These keywords can also be used with any of the iterator-based
looping mechanisms:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ i=0
loop do
i += 1
next if i < 3
print i
break if i > 4
end
!- puts
]]></fullcode>
i=0
loop<nbsp/>do
<nbsp/><nbsp/>i<nbsp/>+=<nbsp/>1
<nbsp/><nbsp/>next<nbsp/>if<nbsp/>i<nbsp/><<nbsp/>3
<nbsp/><nbsp/>print<nbsp/>i
<nbsp/><nbsp/>break<nbsp/>if<nbsp/>i<nbsp/>><nbsp/>4
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
345
</alltt>
</codefragment>
<subsection>Retry</subsection>
<p/>
The <kw>redo</kw> statement causes a loop to repeat the current
iteration. Sometimes, though, you need to wind the loop right back to
the very beginning. The <kw>retry</kw> statement is just the
ticket. <kw>retry</kw> restarts any kind of iterator loop.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ for i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end
]]></fullcode>
for<nbsp/>i<nbsp/>in<nbsp/>1..100
<nbsp/><nbsp/>print<nbsp/>"Now<nbsp/>at<nbsp/>#{i}.<nbsp/>Restart?<nbsp/>"
<nbsp/><nbsp/>retry<nbsp/>if<nbsp/>gets<nbsp/>=~<nbsp/>/^y/i
end
</alltt>
</codefragment>
<p/>
Running this interactively, you might see
<p/>
<codefragment>
<alltt><fullcode><![CDATA[Now at 1. Restart? n
Now at 2. Restart? y
Now at 1. Restart? n
. . .
]]></fullcode>
Now<nbsp/>at<nbsp/>1.<nbsp/>Restart?<nbsp/>n
Now<nbsp/>at<nbsp/>2.<nbsp/>Restart?<nbsp/>y
Now<nbsp/>at<nbsp/>1.<nbsp/>Restart?<nbsp/>n
<nbsp/>.<nbsp/>.<nbsp/>.
</alltt>
</codefragment>
<p/>
<tt>retry</tt> 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/>
<codefragment>
<alltt><fullcode><![CDATA[ def doUntil(cond)
yield
retry unless cond
end
i = 0
doUntil(i > 3) {
print i, " "
i += 1
}
!- puts
]]></fullcode>
def<nbsp/>doUntil(cond)
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>retry<nbsp/>unless<nbsp/>cond
end
<p/>
i<nbsp/>=<nbsp/>0
doUntil(i<nbsp/>><nbsp/>3)<nbsp/>{
<nbsp/><nbsp/>print<nbsp/>i,<nbsp/>"<nbsp/>"
<nbsp/><nbsp/>i<nbsp/>+=<nbsp/>1
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
0<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>4
</alltt>
</codefragment>
<section>Variable Scope and Loops</section>
<p/>
The <kw>while</kw>, <kw>until</kw>, and <kw>for</kw> 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/>
The blocks used by iterators (such as <kw>loop</kw> and <kw>each</kw>) are
a little different. Normally, the local variables created in these
blocks are not accessible outside the block.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ [ 1, 2, 3 ].each do |x|
y = x + 1
end
[ x, y ]
]]></fullcode>
[<nbsp/>1,<nbsp/>2,<nbsp/>3<nbsp/>].each<nbsp/>do<nbsp/>|x|
<nbsp/><nbsp/>y<nbsp/>=<nbsp/>x<nbsp/>+<nbsp/>1
end
[<nbsp/>x,<nbsp/>y<nbsp/>]
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
prog.rb:4: undefined local variable or method `x'<br/>for #<Object:0x4019ac90> (NameError)
</alltt>
</codefragment>
<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/>
<codefragment>
<fullcode><![CDATA[ x = nil
y = nil
[ 1, 2, 3 ].each do |x|
y = x + 1
end
[ x, y ]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>x<nbsp/>=<nbsp/>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt>y<nbsp/>=<nbsp/>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3<nbsp/>].each<nbsp/>do<nbsp/>|x|</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>y<nbsp/>=<nbsp/>x<nbsp/>+<nbsp/>1</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td><tt>[<nbsp/>x,<nbsp/>y<nbsp/>]</tt></td>
<td>»</td>
<td><tt>[3,<nbsp/>4]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
</chapter>
</ppdoc>
|