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 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
|
<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="Containers, Blocks, and Iterators">
A jukebox with one song is unlikely to be popular (except perhaps in
some very, very scary bars), so pretty soon we'll have to start thinking about
producing a catalog of available songs and a playlist of songs waiting
to be played. Both of these are containers: objects that hold
references to one or more other objects.
<p/>
Both the catalog and the playlist need a similar set of methods: add a
song, remove a song, return a list of songs, and so on. The playlist
may perform additional tasks, such as inserting advertising every so
often or keeping track of cumulative play time, but we'll worry
about these things later. In the meantime, it seems like a good idea
to develop some kind of generic <classname>SongList</classname> class, which we can
specialize into catalogs and playlists.
<section>Containers</section>
<p/>
Before we start implementing, we'll need to work out how to store the
list of songs inside a <classname>SongList</classname> object. We have three obvious
choices. We could use the Ruby <classname>Array</classname> type, use the Ruby <classname>Hash</classname> type,
or create our own list structure. Being lazy, for now we'll
look at arrays and hashes, and choose one of these for our class.
<subsection>Arrays</subsection>
<p/>
The class <classname>Array</classname> holds a collection of object references.
Each
object reference occupies a position in the array, identified by a
non-negative integer index.
<p/>
You can create arrays using literals or by explicitly creating an
<classname>Array</classname> object. A literal array is simply a list of objects between
square brackets.
<p/>
<codefragment>
<fullcode><![CDATA[ a = [ 3.14159, "pie", 99 ]
a.type
a.length
a[0]
a[1]
a[2]
a[3]
b = Array.new
b.type
b.length
b[0] = "second"
b[1] = "array"
b
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>3.14159,<nbsp/>"pie",<nbsp/>99<nbsp/>]</tt></td>
</tr>
<tr>
<td><tt>a.type</tt></td>
<td>»</td>
<td><tt>Array</tt></td>
</tr>
<tr>
<td><tt>a.length</tt></td>
<td>»</td>
<td><tt>3</tt></td>
</tr>
<tr>
<td><tt>a[0]</tt></td>
<td>»</td>
<td><tt>3.14159</tt></td>
</tr>
<tr>
<td><tt>a[1]</tt></td>
<td>»</td>
<td><tt>"pie"</tt></td>
</tr>
<tr>
<td><tt>a[2]</tt></td>
<td>»</td>
<td><tt>99</tt></td>
</tr>
<tr>
<td><tt>a[3]</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>b<nbsp/>=<nbsp/>Array.new</tt></td>
</tr>
<tr>
<td><tt>b.type</tt></td>
<td>»</td>
<td><tt>Array</tt></td>
</tr>
<tr>
<td><tt>b.length</tt></td>
<td>»</td>
<td><tt>0</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b[0]<nbsp/>=<nbsp/>"second"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b[1]<nbsp/>=<nbsp/>"array"</tt></td>
</tr>
<tr>
<td><tt>b</tt></td>
<td>»</td>
<td><tt>["second",<nbsp/>"array"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Arrays are indexed using the <tt>[]</tt> operator.
As with most Ruby
operators, this is actually a method (in class <classname>Array</classname>) and hence
can be overridden in subclasses. As the example shows, array indices
start at zero. Index an array with a single integer, and it returns
the object at that position or returns <tt>nil</tt> if nothing's there.
Index an array with a negative integer, and it counts from the
end. This is shown in Figure 4.1 on page 37.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
<codefragment>
<fullcode><![CDATA[ a = [ 1, 3, 5, 7, 9 ]
a[-1]
a[-2]
a[-99]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
<td><tt>a[-1]</tt></td>
<td>»</td>
<td><tt>9</tt></td>
</tr>
<tr>
<td><tt>a[-2]</tt></td>
<td>»</td>
<td><tt>7</tt></td>
</tr>
<tr>
<td><tt>a[-99]</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can also index arrays with a pair of numbers, <tt>[start,<nbsp/>count]</tt>.
This returns a new array consisting of references to <tt>count</tt> objects
starting at position <tt>start</tt>.
<p/>
<codefragment>
<fullcode><![CDATA[ a = [ 1, 3, 5, 7, 9 ]
a[1, 3]
a[3, 1]
a[-3, 2]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
<td><tt>a[1,<nbsp/>3]</tt></td>
<td>»</td>
<td><tt>[3,<nbsp/>5,<nbsp/>7]</tt></td>
</tr>
<tr>
<td><tt>a[3,<nbsp/>1]</tt></td>
<td>»</td>
<td><tt>[7]</tt></td>
</tr>
<tr>
<td><tt>a[-3,<nbsp/>2]</tt></td>
<td>»</td>
<td><tt>[5,<nbsp/>7]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Finally, you can index arrays using ranges, in which start and end
positions are separated by two or three periods. The two-period form
includes the end position, while the three-period form does not.
<p/>
<codefragment>
<fullcode><![CDATA[ a = [ 1, 3, 5, 7, 9 ]
a[1..3]
a[1...3]
a[3..3]
a[-3..-1]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>a<nbsp/>=<nbsp/>[<nbsp/>1,<nbsp/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9<nbsp/>]</tt></td>
</tr>
<tr>
<td><tt>a[1..3]</tt></td>
<td>»</td>
<td><tt>[3,<nbsp/>5,<nbsp/>7]</tt></td>
</tr>
<tr>
<td><tt>a[1...3]</tt></td>
<td>»</td>
<td><tt>[3,<nbsp/>5]</tt></td>
</tr>
<tr>
<td><tt>a[3..3]</tt></td>
<td>»</td>
<td><tt>[7]</tt></td>
</tr>
<tr>
<td><tt>a[-3..-1]</tt></td>
<td>»</td>
<td><tt>[5,<nbsp/>7,<nbsp/>9]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The <tt>[]</tt> operator has a corresponding <tt>[]=</tt> operator, which
lets you set elements in the array. If used with a single integer
index, the element at that position is replaced by whatever is on the
right-hand side of the assignment. Any gaps that result will be filled
with <tt>nil</tt>.
<p/>
<codefragment>
<table>
<tr>
<td>a = [ 1, 3, 5, 7, 9 ]</td>
<td>»</td>
<td>[1, 3, 5, 7, 9]</td>
</tr>
<tr>
<td>a[1] = 'bat'</td>
<td>»</td>
<td>[1, "bat", 5, 7, 9]</td>
</tr>
<tr>
<td>a[-3] = 'cat'</td>
<td>»</td>
<td>[1, "bat", "cat", 7, 9]</td>
</tr>
<tr>
<td>a[3] = [ 9, 8 ]</td>
<td>»</td>
<td>[1, "bat", "cat", [9, 8], 9]</td>
</tr>
<tr>
<td>a[6] = 99</td>
<td>»</td>
<td>[1, "bat", "cat", [9, 8], 9, nil, 99]</td>
</tr>
</table>
<p/>
</codefragment>
<p/>
If the index to <tt>[]=</tt> is two numbers (a start and a length) or a
range, then those elements in the original array are replaced by
whatever is on the right-hand side of the assignment. If the length is
zero, the right-hand side is inserted into the array before the start
position; no elements are removed. If the right-hand side is itself an
array, its elements are used in the replacement.
The array size is automatically adjusted if the index selects a
different number of elements than are available on the right-hand side
of the assignment.
<p/>
<codefragment>
<table>
<tr>
<td>a = [ 1, 3, 5, 7, 9 ]</td>
<td>»</td>
<td>[1, 3, 5, 7, 9]</td>
</tr>
<tr>
<td>a[2, 2] = 'cat'</td>
<td>»</td>
<td>[1, 3, "cat", 9]</td>
</tr>
<tr>
<td>a[2, 0] = 'dog'</td>
<td>»</td>
<td>[1, 3, "dog", "cat", 9]</td>
</tr>
<tr>
<td>a[1, 1] = [ 9, 8, 7 ]</td>
<td>»</td>
<td>[1, 9, 8, 7, "dog", "cat", 9]</td>
</tr>
<tr>
<td>a[0..3] = []</td>
<td>»</td>
<td>["dog", "cat", 9]</td>
</tr>
<tr>
<td>a[5] = 99</td>
<td>»</td>
<td>["dog", "cat", 9, nil, nil, 99]</td>
</tr>
</table>
<p/>
</codefragment>
<p/>
Arrays have a large number of other useful methods. Using these,
you can treat arrays as stacks, sets, queues,
dequeues, and fifos. A complete list of array methods starts
on page 282.
<subsection>Hashes</subsection>
<p/>
Hashes (sometimes known as associative arrays or dictionaries) are
similar to arrays, in that they are indexed collectives of object
references.
<p/>
However, while you index arrays with integers, you can
index a hash with objects of any type: strings, regular expressions,
and so on. When you store a value in a hash, you actually supply two
objects---the key and the value. You can subsequently retrieve the
value by indexing the hash with the same key. The values in a hash can
be any objects of any type. The example that follows uses hash literals: a
list of <em>key</em><nbsp/><tt>=></tt><nbsp/><em>value</em> pairs between braces.
<p/>
<codefragment>
<fullcode><![CDATA[ h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
h.length
h['dog']
h['cow'] = 'bovine'
h[12] = 'dodecine'
h['cat'] = 99
h
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>h<nbsp/>=<nbsp/>{<nbsp/>'dog'<nbsp/>=><nbsp/>'canine',<nbsp/>'cat'<nbsp/>=><nbsp/>'feline',<nbsp/>'donkey'<nbsp/>=><nbsp/>'asinine'<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td><tt>h.length</tt></td>
<td>»</td>
<td><tt>3</tt></td>
</tr>
<tr>
<td><tt>h['dog']</tt></td>
<td>»</td>
<td><tt>"canine"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h['cow']<nbsp/>=<nbsp/>'bovine'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h[12]<nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>'dodecine'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h['cat']<nbsp/>=<nbsp/>99</tt></td>
</tr>
<tr>
<td><tt>h</tt></td>
<td>»</td>
<td><tt>{"cow"=>"bovine",<nbsp/>12=>"dodecine",<nbsp/>"dog"=>"canine",<nbsp/>"donkey"=>"asinine",<nbsp/>"cat"=>99}</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Compared with arrays, hashes have one significant advantage: they can
use any object as an index. However, they also have a significant
disadvantage: their elements are not ordered, so you cannot easily use
a hash as a stack or a queue.
<p/>
You'll find that hashes are one of the most commonly used data
structures in Ruby. A full list of the methods implemented by class
<classname>Hash</classname> starts on page 321.
<subsection>Implementing a SongList Container</subsection>
<p/>
After that little diversion into arrays and hashes, we're now ready to
implement the jukebox's <classname>SongList</classname>. Let's invent a basic list of
methods we need in our <classname>SongList</classname>. We'll want to add to it as we go
along, but it will do for now.
<p/>
<dl>
<dt>append( aSong ) » list</dt><dd>
Append the given song to the list.
</dd><dt>deleteFirst() » aSong</dt><dd>
Remove the first song from the list, returning that song.
</dd><dt>deleteLast() » aSong</dt><dd>
Remove the last song from the list, returning that song.
</dd><dt>[ anIndex } » aSong</dt><dd>
Return the song identified by <obj>anIndex</obj>, which may be an
integer index or a song title.
</dd></dl>
<p/>
This list gives us a clue to the implementation. The ability to append
songs at the end, and remove them from both the front and end, suggests a
dequeue---a double-ended queue---which we know we can implement using
an <classname>Array</classname>. Similarly, the ability to return a song at an integer
position in the list is supported by arrays.
<p/>
However, there's also the
need to be able to retrieve songs by title, which might suggest using a
hash, with the title as a key and the song as a value. Could we use a
hash? Well, possibly, but there are problems. First a hash is
unordered, so we'd probably need to use an ancillary array to keep
track of the list. A bigger problem is that a hash does not support
multiple keys with the same value. That would be a problem for our
playlist, where the same song might be queued up for playing multiple
times. So, for now we'll stick with an array of songs, searching it
for titles when needed. If this becomes a performance bottleneck, we
can always add some kind of hash-based lookup later.
<p/>
We'll start our class with a basic <meth>initialize</meth> method, which
creates the <classname>Array</classname> we'll use to hold the songs and stores a
reference to it in the instance variable <var>@songs</var>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
class SongList
def initialize
@songs = Array.new
!- @index = WordIndex.new
end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>@songs<nbsp/>=<nbsp/>Array.new
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The <cim><front>SongList</front><back>append</back></cim> method adds the given song to the end of the
<var>@songs</var> array. It also returns <obj>self</obj>, a reference to the
current <classname>SongList</classname> object. This is a useful convention, as it lets
us chain together multiple calls to <meth>append</meth>. We'll see an
example of this later.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
def append(aSong)
@songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
self
end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>append(aSong)
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.push(aSong)
<nbsp/><nbsp/><nbsp/><nbsp/>self
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Then we'll add the <meth>deleteFirst</meth> and <meth>deleteLast</meth>
methods, trivially implemented using <cim><file>array</file><front>Array</front><back>shift</back><mref>shift</mref></cim> and
<cim><file>array</file><front>Array</front><back>pop</back><mref>pop</mref></cim>, respectively.
<p/>
<codefragment>
<alltt><fullcode><
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>deleteFirst
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.shift
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>deleteLast
<nbsp/><nbsp/><nbsp/><nbsp/>@songs.pop
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
At this point, a quick test might be in order. First, we'll append
four songs to the list. Just to show off, we'll use the fact that
<meth>append</meth> returns the <classname>SongList</classname> object to chain together
these method calls.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
!-class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
!-end
!-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
list = SongList.new
list.
append(Song.new('title1', 'artist1', 1)).
append(Song.new('title2', 'artist2', 2)).
append(Song.new('title3', 'artist3', 3)).
append(Song.new('title4', 'artist4', 4))
!-list[0]
!-list[2]
!-list[9]
!-list.deleteFirst
!-list.deleteFirst
!-list.deleteLast
!-list.deleteLast
!-list.deleteLast
]]></fullcode>
list<nbsp/>=<nbsp/>SongList.new
list.
<nbsp/><nbsp/>append(Song.new('title1',<nbsp/>'artist1',<nbsp/>1)).
<nbsp/><nbsp/>append(Song.new('title2',<nbsp/>'artist2',<nbsp/>2)).
<nbsp/><nbsp/>append(Song.new('title3',<nbsp/>'artist3',<nbsp/>3)).
<nbsp/><nbsp/>append(Song.new('title4',<nbsp/>'artist4',<nbsp/>4))
</alltt>
</codefragment>
<p/>
Then we'll check that songs are taken from the start and end of the
list correctly, and that <tt>nil</tt> is returned when the list becomes
empty.
<p/>
<codefragment>
<fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
!-class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
!-end
!-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
!-list = SongList.new
!-list.
!- append(Song.new('title1', 'artist1', 1)).
!- append(Song.new('title2', 'artist2', 2)).
!- append(Song.new('title3', 'artist3', 3)).
!- append(Song.new('title4', 'artist4', 4))
!-list[0]
!-list[2]
!-list[9]
list.deleteFirst
list.deleteFirst
list.deleteLast
list.deleteLast
list.deleteLast
]]></fullcode><rubycode>
<tr>
<td><tt>list.deleteFirst</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title1--artist1<nbsp/>(1)</tt></td>
</tr>
<tr>
<td><tt>list.deleteFirst</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title2--artist2<nbsp/>(2)</tt></td>
</tr>
<tr>
<td><tt>list.deleteLast</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title4--artist4<nbsp/>(4)</tt></td>
</tr>
<tr>
<td><tt>list.deleteLast</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title3--artist3<nbsp/>(3)</tt></td>
</tr>
<tr>
<td><tt>list.deleteLast</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
So far so good. Our next method is <tt>[]</tt>, which accesses elements
by index. If the index is a number (which we check using
<cim><file>object</file><front>Object</front><back>kind_of?</back><mref>kind_of_qm</mref></cim>), we just return the
element at that position.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
def [](key)
if key.kind_of?(Integer)
@songs[key]
else
# ...
end
end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Again, testing this is pretty trivial.
<p/>
<codefragment>
<fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
!-class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
!-end
!-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
!-list = SongList.new
!-list.
!- append(Song.new('title1', 'artist1', 1)).
!- append(Song.new('title2', 'artist2', 2)).
!- append(Song.new('title3', 'artist3', 3)).
!- append(Song.new('title4', 'artist4', 4))
list[0]
list[2]
list[9]
!-list.deleteFirst
!-list.deleteFirst
!-list.deleteLast
!-list.deleteLast
!-list.deleteLast
]]></fullcode><rubycode>
<tr>
<td><tt>list[0]</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title1--artist1<nbsp/>(1)</tt></td>
</tr>
<tr>
<td><tt>list[2]</tt></td>
<td>»</td>
<td><tt>Song:<nbsp/>title3--artist3<nbsp/>(3)</tt></td>
</tr>
<tr>
<td><tt>list[9]</tt></td>
<td>»</td>
<td><tt>nil</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Now we need to add the facility that lets us look up a song by
title. This is going to involve scanning through the songs in the
list, checking the title of each. To do this, we first need to spend a
couple of pages looking at one of Ruby's neatest features: iterators.<section>Blocks and Iterators</section>
<p/>
So, our next problem with <classname>SongList</classname> is to implement the code in
method <meth>[]</meth> that takes a string and searches for a song with
that title. This seems straightforward: we have an array of songs, so
we just go through it one element at a time, looking for a match.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
!-class 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
class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
def [](key)
if key.kind_of?(Integer)
return @songs[key]
else
for i in 0...@songs.length
return @songs[i] if key == @songs[i].name
end
end
return nil
end
!- def [](key)
!- if key.kind_of?(Integer)
!- result = @songs[key]
!- else
!- result = @songs.find { |aSong| key == aSong.name }
!- end
!- return result
!- end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>for<nbsp/>i<nbsp/>in<nbsp/>0...@songs.length
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[i]<nbsp/>if<nbsp/>key<nbsp/>==<nbsp/>@songs[i].name
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>nil
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This works, and it looks comfortingly familiar: a <tt>for</tt> loop
iterating over an array. What could be more natural?
<p/>
It turns out there <em>is</em> something more natural. In a way,
our <kw>for</kw> loop is somewhat too intimate with the array; it asks for
a length, then retrieves values in turn until it finds a match. Why
not just ask the array to apply a test to each of its members?
That's just what the <tt>find</tt> method in <classname>Array</classname> does.
<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
!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
class SongList
!- def initialize
!- @songs = Array.new
!- @index = WordIndex.new
!- end
!- def append(aSong)
!- @songs.push(aSong)
!- @index.index(aSong, aSong.name, aSong.artist)
!- self
!- end
!- def deleteFirst
!- @songs.shift
!- end
!- def deleteLast
!- @songs.pop
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- @songs[key]
!- else
!- # ...
!- end
!- end
!- def [](key)
!- if key.kind_of?(Integer)
!- return @songs[key]
!- else
!- for i in 0...@songs.length
!- return @songs[i] if key == @songs[i].name
!- end
!- end
!- return nil
!- end
def [](key)
if key.kind_of?(Integer)
result = @songs[key]
else
result = @songs.find { |aSong| key == aSong.name }
end
return result
end
!- def lookup(aWord)
!- @index.lookup(aWord)
!- end
!- def createSearch(name, params)
!- # ...
!- end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>@songs[key]
<nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>result<nbsp/>=<nbsp/>@songs.find<nbsp/>{<nbsp/>|aSong|<nbsp/>key<nbsp/>==<nbsp/>aSong.name<nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>result
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
We could use <tt>if</tt> as a statement modifier to shorten the
code even more.
<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
!- class WordIndex
!- def initialize
!- @index = Hash.new(nil)
!- end
!- def index(anObject, *phrases)
!- phrases.each do |aPhrase|
!- aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
!- aWord.downcase!
!- @index[aWord] = [] if @index[aWord].nil?
!- @index[aWord].push(anObject)
!- end
!- end
!- end
!- def lookup(aWord)
!- @index[aWord.downcase]
!- end
!- end
class SongList
def [](key)
return @songs[key] if key.kind_of?(Integer)
return @songs.find { |aSong| aSong.name == key }
end
end
]]></fullcode>
class<nbsp/>SongList
<nbsp/><nbsp/>def<nbsp/>[](key)
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs[key]<nbsp/>if<nbsp/>key.kind_of?(Integer)
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@songs.find<nbsp/>{<nbsp/>|aSong|<nbsp/>aSong.name<nbsp/>==<nbsp/>key<nbsp/>}
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The method <meth>find</meth> is an iterator---a method that invokes a
block of code repeatedly. Iterators and code blocks are among the
more interesting features of Ruby, so let's spend a while looking into
them (and in the process we'll find out exactly what that line of code
in our <tt>[]</tt> method actually does).
<subsection>Implementing Iterators</subsection>
<p/>
A Ruby iterator is simply a method that can invoke a block of code.
At first sight, a block in Ruby looks just like a block in C, Java,
or Perl. Unfortunately, in this case looks are deceiving---a Ruby
block <em>is</em> a way of grouping statements, but not in the
conventional way.
<p/>
First, a block may appear only in the source adjacent to a method
call; the block is written starting on the same line as the method's
last parameter. Second, the code in the block is not executed at the
time it is encountered. Instead, Ruby remembers the context in which
the block appears (the local variables, the current object, and so
on), and then enters the method. This is where the magic starts.
<p/>
Within the method, the block may be invoked, almost as if it were a
method itself, using the <kw>yield</kw> statement.
Whenever a <kw>yield</kw>
is executed, it invokes the code in the block. When the block
exits, control picks back up immediately after the
<kw>yield</kw>.<footnote>Programming-language buffs will be pleased to
know that the keyword <kw>yield</kw> was chosen to echo the <kw>yield</kw>
function in Liskov's language CLU, a language that is over 20
years old and yet contains features that still haven't been widely
exploited by the CLU-less.</footnote> Let's start with a trivial example.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ def threeTimes
yield
yield
yield
end
threeTimes { puts "Hello" }
]]></fullcode>
def<nbsp/>threeTimes
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>yield
<nbsp/><nbsp/>yield
end
threeTimes<nbsp/>{<nbsp/>puts<nbsp/>"Hello"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Hello
Hello
Hello
</alltt>
</codefragment>
<p/>
The block (the code between the braces) is associated with the call to
the method <meth>threeTimes</meth>. Within this method, <kw>yield</kw> is
called three times in a row. Each time, it invokes the code in the
block, and a cheery greeting is printed. What makes blocks interesting,
however, is that you can pass parameters to them and receive values
back from them. For example, we could write a simple function that
returns members of the Fibonacci series up to a certain
value.<footnote>The basic Fibonacci series is a sequence of integers,
starting with two 1's, in which each subsequent term is the sum
of the two preceding terms. The series is sometimes used in sorting
algorithms and in analyzing natural phenomena.</footnote>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[def fibUpTo(max)
i1, i2 = 1, 1 # parallel assignment
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
fibUpTo(1000) { |f| print f, " " }
!- puts
]]></fullcode>
def<nbsp/>fibUpTo(max)
<nbsp/><nbsp/>i1,<nbsp/>i2<nbsp/>=<nbsp/>1,<nbsp/>1<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>parallel<nbsp/>assignment
<nbsp/><nbsp/>while<nbsp/>i1<nbsp/><=<nbsp/>max
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>i1
<nbsp/><nbsp/><nbsp/><nbsp/>i1,<nbsp/>i2<nbsp/>=<nbsp/>i2,<nbsp/>i1+i2
<nbsp/><nbsp/>end
end
fibUpTo(1000)<nbsp/>{<nbsp/>|f|<nbsp/>print<nbsp/>f,<nbsp/>"<nbsp/>"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1<nbsp/>1<nbsp/>2<nbsp/>3<nbsp/>5<nbsp/>8<nbsp/>13<nbsp/>21<nbsp/>34<nbsp/>55<nbsp/>89<nbsp/>144<nbsp/>233<nbsp/>377<nbsp/>610<nbsp/>987
</alltt>
</codefragment>
<p/>
In this example, the <kw>yield</kw> statement has a parameter.
This value
is passed to the associated block. In the definition of the block, the
argument list appears between vertical bars. In this instance, the
variable <var>f</var> receives the value passed to the <kw>yield</kw>, so the
block prints successive members of the series. (This example also
shows parallel assignment in action. We'll come back to this
on page 77.) Although it is common to pass just one
value to a block, this is not a requirement; a block may have any
number of arguments. What happens if a block has a different number
of parameters than are given to the yield? By a staggering
coincidence, the rules we discuss under parallel assignment come into
play (with a slight twist: multiple parameters passed to a <kw>yield</kw>
are converted to an array if the block has just one argument).
<p/>
Parameters to a block may be existing local variables; if so, the new value of the variable will be
retained after the block completes. This may lead to unexpected
behavior, but there is also a performance gain to be had by using
variables that already exist.<footnote>For more information on this
and other ``gotchas,'' see the list beginning
on page 129; more performance information begins
on page 130.</footnote>
<p/>
A block may also return a value to the method. The value of the last
expression evaluated in the block is passed back to the method as the
value of the <tt>yield</tt>. This is how the <meth>find</meth> method used by class
<classname>Array</classname> works.<footnote>The <meth>find</meth> method is actually defined
in module <modulename>Enumerable</modulename>, which is mixed into class <classname>Array</classname>.</footnote> Its
implementation would look something like the following.
<p/>
<codefragment>
<fullcode><![CDATA[class Array
def find
for i in 0...size
value = self[i]
return value if yield(value)
end
return nil
end
end
[1, 3, 5, 7, 9].find {|v| v*v > 30 }
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Array</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>find</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>for<nbsp/>i<nbsp/>in<nbsp/>0...size</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>value<nbsp/>=<nbsp/>self[i]</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>value<nbsp/>if<nbsp/>yield(value)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>nil</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/>3,<nbsp/>5,<nbsp/>7,<nbsp/>9].find<nbsp/>{|v|<nbsp/>v*v<nbsp/>><nbsp/>30<nbsp/>}</tt></td>
<td>»</td>
<td><tt>7</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This passes successive elements of the array to the associated block. If
the block returns <const>true</const>, the method returns the corresponding
element. If no element matches, the method returns <tt>nil</tt>. The example shows
the benefit of this approach to iterators. The <classname>Array</classname> class does
what it does best, accessing array elements, leaving the application
code to concentrate on its particular requirement (in this case,
finding an entry that meets some mathematical criteria).
<p/>
Some iterators are common to many types of Ruby collections. We've
looked at <meth>find</meth> already. Two others are <meth>each</meth> and
<meth>collect</meth>.
<meth>each</meth> is probably the simplest iterator---all it does is yield
successive elements of its collection.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ [ 1, 3, 5 ].each { |i| puts i }
!-puts
]]></fullcode>
[<nbsp/>1,<nbsp/>3,<nbsp/>5<nbsp/>].each<nbsp/>{<nbsp/>|i|<nbsp/>puts<nbsp/>i<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
1
3
5
<p/>
</alltt>
</codefragment>
<p/>
The <meth>each</meth> iterator has a special place in Ruby;
on page
87 we'll describe how it's used as the basis of the
language's <kw>for</kw> loop, and starting on page 104 we'll see how
defining an <meth>each</meth> method can add a whole lot more
functionality to your class for free.
<p/>
Another common iterator is <meth>collect</meth>, which takes each element
from the collection and passes it to the block. The results returned
by the block are
used to construct a new array. For instance:
<p/>
<codefragment>
<fullcode><![CDATA[ ["H", "A", "L"].collect { |x| x.succ }
]]></fullcode><rubycode>
<tr>
<td><tt>["H",<nbsp/>"A",<nbsp/>"L"].collect<nbsp/>{<nbsp/>|x|<nbsp/>x.succ<nbsp/>}</tt></td>
<td>»</td>
<td><tt>["I",<nbsp/>"B",<nbsp/>"M"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Ruby Compared with C++ and Java</subsection>
<p/>
It's worth spending a paragraph comparing Ruby's approach to iterators
to that of C++ and Java. In the Ruby approach, the iterator is simply
a method, identical to any other, that happens to call <kw>yield</kw>
whenever it generates a new value. The thing that uses the iterator is
simply a block of code associated with this method. There is no need
to generate helper classes to carry the iterator state, as in Java and
C++. In this, as in many other ways, Ruby is a transparent
language.
When you write a Ruby program, you concentrate on getting
the job done, not on building scaffolding to support the language
itself.
<p/>
Iterators are not limited to accessing existing data in arrays and
hashes. As we saw in the Fibonacci example, an iterator can return
derived values. This capability is used by the Ruby input/output
classes, which implement
an iterator interface returning successive lines (or bytes) in an I/O
stream.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ f = File.open("testfile")
f.each do |line|
print line
end
f.close
]]></fullcode>
f<nbsp/>=<nbsp/>File.open("testfile")
f.each<nbsp/>do<nbsp/>|line|
<nbsp/><nbsp/>print<nbsp/>line
end
f.close
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>line<nbsp/>one
This<nbsp/>is<nbsp/>line<nbsp/>two
This<nbsp/>is<nbsp/>line<nbsp/>three
And<nbsp/>so<nbsp/>on...
</alltt>
</codefragment>
<p/>
Let's look at just one more iterator implementation. The Smalltalk
language also supports iterators over collections. If you ask
Smalltalk programmers to sum the elements in an array, it's likely that
they'd use the <meth>inject</meth> function.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[sumOfValues "Smalltalk method"
^self values
inject: 0
into: [ :sum :element | sum + element value]
]]></fullcode>
sumOfValues<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"Smalltalk<nbsp/>method"
<nbsp/><nbsp/><nbsp/><nbsp/>^self<nbsp/>values
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>inject:<nbsp/>0
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>into:<nbsp/>[<nbsp/>:sum<nbsp/>:element<nbsp/>|<nbsp/>sum<nbsp/>+<nbsp/>element<nbsp/>value]
</alltt>
</codefragment>
<p/>
<meth>inject</meth> works like this. The first time the associated block
is called, <var>sum</var> is set to <meth>inject</meth>'s parameter (zero in this case),
and <var>element</var> is set to the first element in the array. The second
and subsequent times the block is called, <var>sum</var> is set to the
value returned by the block on the previous call. This way, <var>sum</var>
can be used to keep a running total. The final value of <meth>inject</meth> is the
value returned by the block the last time it was called.
<p/>
Ruby does not have an <meth>inject</meth> method, but
it's easy to write one. In this case we'll add it to the <classname>Array</classname>
class, while on page 102 we'll see how to make it more
generally available.
<p/>
<codefragment>
<fullcode><![CDATA[ class Array
def inject(n)
each { |value| n = yield(n, value) }
n
end
def sum
inject(0) { |n, value| n + value }
end
def product
inject(1) { |n, value| n * value }
end
end
[ 1, 2, 3, 4, 5 ].sum
[ 1, 2, 3, 4, 5 ].product
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Array</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>inject(n)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>each<nbsp/>{<nbsp/>|value|<nbsp/>n<nbsp/>=<nbsp/>yield(n,<nbsp/>value)<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>n</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>sum</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>inject(0)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>+<nbsp/>value<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>product</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>inject(1)<nbsp/>{<nbsp/>|n,<nbsp/>value|<nbsp/>n<nbsp/>*<nbsp/>value<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>].sum</tt></td>
<td>»</td>
<td><tt>15</tt></td>
</tr>
<tr>
<td><tt>[<nbsp/>1,<nbsp/>2,<nbsp/>3,<nbsp/>4,<nbsp/>5<nbsp/>].product</tt></td>
<td>»</td>
<td><tt>120</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Although blocks are often the target of an iterator, they also have
other uses. Let's look at a few.
<subsection>Blocks for Transactions</subsection>
<p/>
Blocks can be used to define a chunk of code that must be run under
some kind of transactional control.
For example, you'll often open a
file, do something with its contents, and then want to ensure that the
file is closed when you finish. Although you can do this using
conventional code, there's an argument for making the file responsible
for closing itself. We can do this with blocks. A naive implementation
(ignoring error handling) might look something like the following.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ class File
def File.openAndProcess(*args)
f = File.open(*args)
yield f
f.close()
end
end
File.openAndProcess("testfile", "r") do |aFile|
print while aFile.gets
end
]]></fullcode>
class<nbsp/>File
<nbsp/><nbsp/>def<nbsp/>File.openAndProcess(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>f<nbsp/>=<nbsp/>File.open(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>f
<nbsp/><nbsp/><nbsp/><nbsp/>f.close()
<nbsp/><nbsp/>end
end
<p/>
File.openAndProcess("testfile",<nbsp/>"r")<nbsp/>do<nbsp/>|aFile|
<nbsp/><nbsp/>print<nbsp/>while<nbsp/>aFile.gets
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>line<nbsp/>one
This<nbsp/>is<nbsp/>line<nbsp/>two
This<nbsp/>is<nbsp/>line<nbsp/>three
And<nbsp/>so<nbsp/>on...
</alltt>
</codefragment>
<p/>
This small example illustrates a number of techniques. The
<meth>openAndProcess</meth> method is a <em>class method</em>---it may be
called independent of any particular <classname>File</classname> object. We want it to
take the same arguments as the conventional <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> method,
but we don't really care what those arguments are. Instead, we
specified the arguments as <tt>*args</tt>, meaning ``collect the actual
parameters passed to the method into an array.'' We then call
<tt>File.open</tt>, passing it <tt>*args</tt> as a parameter. This expands the
array back into individual parameters. The net result is that
<tt>openAndProcess</tt> transparently passes whatever parameters it
received to <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm>.
<p/>
Once the file has been opened, <tt>openAndProcess</tt> calls <meth>yield</meth>,
passing the open file object to the block. When the block returns, the
file is closed. In this way, the responsibility for closing an open
file has been passed from the user of file objects back to the files
themselves.
<p/>
Finally, this example uses <kw>do</kw>...<kw>end</kw> to define a block. The only
difference between this notation and using braces to define blocks is
precedence: <kw>do</kw>...<kw>end</kw> binds lower than ``{...}''. We
discuss the impact of this on page 236.
<p/>
The technique of having files manage their own lifecycle is so useful
that the class <classname>File</classname> supplied with Ruby supports it directly. If
<ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> has an associated block, then that block will be
invoked with a file object, and the file will be closed when the block
terminates. This is interesting, as it means that <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> has
two different behaviors: when called with a block, it executes the
block and closes the file. When called without a block, it returns the
file object. This is made possible by the method
<mmm><file>kernel</file><front>Kernel</front><back>block_given?</back><mref>block_given_qm</mref></mmm>, which returns <const>true</const> if a block is associated
with the current method. Using it, you could implement <ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm>
(again, ignoring error handling) using something like the following.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ class File
def File.myOpen(*args)
aFile = File.new(*args)
# If there's a block, pass in the file and close
# the file when it returns
if block_given?
yield aFile
aFile.close
aFile = nil
end
return aFile
end
end
]]></fullcode>
class<nbsp/>File
<nbsp/><nbsp/>def<nbsp/>File.myOpen(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>aFile<nbsp/>=<nbsp/>File.new(*args)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>If<nbsp/>there's<nbsp/>a<nbsp/>block,<nbsp/>pass<nbsp/>in<nbsp/>the<nbsp/>file<nbsp/>and<nbsp/>close
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>the<nbsp/>file<nbsp/>when<nbsp/>it<nbsp/>returns
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>block_given?
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>aFile
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>aFile.close
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>aFile<nbsp/>=<nbsp/>nil
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>aFile
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<subsection>Blocks Can Be Closures</subsection>
<p/>
Let's get back to our jukebox for a moment (remember the
jukebox?).
At some point we'll be working on the code that handles the
user interface---the buttons that people press to select songs and
control the jukebox. We'll need to associate actions with those
buttons: press <smallfont>STOP</smallfont> and the music stops. It turns out that
Ruby's blocks are a convenient way to do this. Let's start out by
assuming that the people who made the hardware implemented a Ruby
extension that gives us a basic button
class. (We talk about extending Ruby beginning on page 171.)
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!- def initialize(label)
!- end
!-end
bStart = Button.new("Start")
bPause = Button.new("Pause")
# ...
]]></fullcode>
bStart<nbsp/>=<nbsp/>Button.new("Start")
bPause<nbsp/>=<nbsp/>Button.new("Pause")
#<nbsp/>...
</alltt>
</codefragment>
<p/>
What happens when the user presses one of our buttons? In the
<classname>Button</classname> class, the hardware folks rigged things so that a
callback method, <meth>buttonPressed</meth>, will be invoked.
The obvious way of adding functionality to these buttons is to create
subclasses of <classname>Button</classname> and have each subclass implement its own
<meth>buttonPressed</meth> method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!- def initialize(label)
!- end
!-end
class StartButton < Button
def initialize
super("Start") # invoke Button's initialize
end
def buttonPressed
# do start actions...
end
end
bStart = StartButton.new
]]></fullcode>
class<nbsp/>StartButton<nbsp/><<nbsp/>Button
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>super("Start")<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>invoke<nbsp/>Button's<nbsp/>initialize
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>buttonPressed
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>do<nbsp/>start<nbsp/>actions...
<nbsp/><nbsp/>end
end
<p/>
bStart<nbsp/>=<nbsp/>StartButton.new
</alltt>
</codefragment>
<p/>
There are two problems here. First, this will lead to a large number
of subclasses. If the interface to <classname>Button</classname> changes, this could
involve us in a lot of maintenance. Second, the actions performed when
a button is pressed are expressed at the wrong level; they are not a
feature of the button, but are a feature of the jukebox that uses the
buttons. We can fix both of these problems using blocks.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Button
!- def initialize(label)
!- end
!-end
!-songList = nil
class JukeboxButton < Button
def initialize(label, &action)
super(label)
@action = action
end
def buttonPressed
@action.call(self)
end
end
bStart = JukeboxButton.new("Start") { songList.start }
bPause = JukeboxButton.new("Pause") { songList.pause }
]]></fullcode>
class<nbsp/>JukeboxButton<nbsp/><<nbsp/>Button
<nbsp/><nbsp/>def<nbsp/>initialize(label,<nbsp/>&action)
<nbsp/><nbsp/><nbsp/><nbsp/>super(label)
<nbsp/><nbsp/><nbsp/><nbsp/>@action<nbsp/>=<nbsp/>action
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>buttonPressed
<nbsp/><nbsp/><nbsp/><nbsp/>@action.call(self)
<nbsp/><nbsp/>end
end
<p/>
bStart<nbsp/>=<nbsp/>JukeboxButton.new("Start")<nbsp/>{<nbsp/>songList.start<nbsp/>}
bPause<nbsp/>=<nbsp/>JukeboxButton.new("Pause")<nbsp/>{<nbsp/>songList.pause<nbsp/>}
</alltt>
</codefragment>
<p/>
The key to all this is the second parameter to
<cim><front>JukeboxButton</front><back>initialize</back></cim>. If the last parameter in a method
definition is prefixed with an ampersand (such as <tt>&action</tt>),
Ruby
looks for a code block whenever that method is called. That code block
is converted to an object of class <classname>Proc</classname> and assigned to the
parameter. You can then treat the parameter as any other variable. In
our example, we assigned it to the instance variable <var>@action</var>.
When the callback method <meth>buttonPressed</meth> is invoked, we use the
<cim><file>proc</file><front>Proc</front><back>call</back><mref>call</mref></cim> method on that object to invoke the block.
<p/>
So what exactly do we have when we create a <classname>Proc</classname> object? The
interesting thing is that it's more than just a chunk of code.
Associated with a block (and hence a <classname>Proc</classname> object) is all the
context in which the block was <em>defined</em>: the value of
<const>self</const>, and the methods, variables, and constants in scope. Part
of the magic of Ruby is that the block can still use all this original
scope information even if the environment in which it was defined
would otherwise have disappeared. In other languages, this facility
is called a <em>closure</em>.
<p/>
Let's look at a contrived example. This example uses the method
<meth>proc</meth>,
which converts a block to a <classname>Proc</classname> object.
<p/>
<codefragment>
<fullcode><![CDATA[ def nTimes(aThing)
return proc { |n| aThing * n }
end
p1 = nTimes(23)
p1.call(3)
p1.call(4)
p2 = nTimes("Hello ")
p2.call(3)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>def<nbsp/>nTimes(aThing)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>return<nbsp/>proc<nbsp/>{<nbsp/>|n|<nbsp/>aThing<nbsp/>*<nbsp/>n<nbsp/>}</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>p1<nbsp/>=<nbsp/>nTimes(23)</tt></td>
</tr>
<tr>
<td><tt>p1.call(3)</tt></td>
<td>»</td>
<td><tt>69</tt></td>
</tr>
<tr>
<td><tt>p1.call(4)</tt></td>
<td>»</td>
<td><tt>92</tt></td>
</tr>
<tr>
<td colspan="3"><tt>p2<nbsp/>=<nbsp/>nTimes("Hello<nbsp/>")</tt></td>
</tr>
<tr>
<td><tt>p2.call(3)</tt></td>
<td>»</td>
<td><tt>"Hello<nbsp/>Hello<nbsp/>Hello<nbsp/>"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The method <meth>nTimes</meth> returns a <classname>Proc</classname> object that references
the method's parameter, <tt>aThing</tt>. Even though that parameter is out
of scope by the time the block is called, the parameter remains
accessible to the block.
<p/>
</chapter>
</ppdoc>
|