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
|
<html><title>Programming Ruby: The Pragmatic Programmer's Guide</title><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><STYLE TYPE="text/css"><!--
BODY { margin-left: 1in;
width: 6in;
font-family: helvetica, arial, sans-serif;
}
H1 { color: #000080;
font-family: helvetica, arial, sans-serif;
font-size: 22pt;
margin-left: 0in
}
H2 { color: #000080; font: bold x-large helvetica, sans-serif;
margin-left: 0in }
H3 { color: #000080; font: bold large helvetica, sans-serif; }
H4 { color: #000080; font: italic large helvetica, sans-serif; }
.ruby { background: #fff0f0 }
.header { color: white }
.subheader { color: #ffdddd }
.sidebar { width: 6in }
span.sans { font-family: helvetica, arial, sans-serif }
-->
</STYLE><table bgcolor="#a03030" cellpadding="3" border="0" cellspacing="0"><tr><td colspan="3"><table bgcolor="#902020" cellpadding="20"><tr><td><h1 class="header">Programming Ruby</h1><h3 class="subheader">The Pragmatic Programmer's Guide</h3></td></tr></table></td></tr><tr><td width="33%" align="left"><a class="subheader" href="tut_classes.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_stdtypes.html">Next ></a><br></td></tr></table></head><body bgcolor="white">
<!--
Copyright (c) 2001 by Addison Wesley Longman. This
material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or
later (the latest version is presently available at
http://www.opencontent.org/openpub/).
-->
<h1>Containers, Blocks, and Iterators</h1><hr><br>
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></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 <code>SongList</code> class, which we can
specialize into catalogs and playlists.
<h2>Containers</h2>
<P></P>
Before we start implementing, we'll need to work out how to store the
list of songs inside a <code>SongList</code> object. We have three obvious
choices. We could use the Ruby <code>Array</code> type, use the Ruby <code>Hash</code> 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.
<h3>Arrays</h3>
<P></P>
The class <code>Array</code> holds a collection of object references.
Each
object reference occupies a position in the array, identified by a
non-negative integer index.
<P></P>
You can create arrays using literals or by explicitly creating an
<code>Array</code> object. A literal array is simply a list of objects between
square brackets.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = [ 3.14159, "pie", 99 ]</code></td>
</tr>
<tr>
<td valign="top"><code>a.type</code></td>
<td valign="top"></td>
<td valign="top"><code>Array</code></td>
</tr>
<tr>
<td valign="top"><code>a.length</code></td>
<td valign="top"></td>
<td valign="top"><code>3</code></td>
</tr>
<tr>
<td valign="top"><code>a[0]</code></td>
<td valign="top"></td>
<td valign="top"><code>3.14159</code></td>
</tr>
<tr>
<td valign="top"><code>a[1]</code></td>
<td valign="top"></td>
<td valign="top"><code>"pie"</code></td>
</tr>
<tr>
<td valign="top"><code>a[2]</code></td>
<td valign="top"></td>
<td valign="top"><code>99</code></td>
</tr>
<tr>
<td valign="top"><code>a[3]</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>b = Array.new</code></td>
</tr>
<tr>
<td valign="top"><code>b.type</code></td>
<td valign="top"></td>
<td valign="top"><code>Array</code></td>
</tr>
<tr>
<td valign="top"><code>b.length</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>b[0] = "second"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>b[1] = "array"</code></td>
</tr>
<tr>
<td valign="top"><code>b</code></td>
<td valign="top"></td>
<td valign="top"><code>["second", "array"]</code></td>
</tr>
</table>
<P></P>
<P></P>
Arrays are indexed using the <code>[]</code> operator.
As with most Ruby
operators, this is actually a method (in class <code>Array</code>) 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 <code>nil</code> 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></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>Figure not available...</td></tr></table>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = [ 1, 3, 5, 7, 9 ]</code></td>
</tr>
<tr>
<td valign="top"><code>a[-1]</code></td>
<td valign="top"></td>
<td valign="top"><code>9</code></td>
</tr>
<tr>
<td valign="top"><code>a[-2]</code></td>
<td valign="top"></td>
<td valign="top"><code>7</code></td>
</tr>
<tr>
<td valign="top"><code>a[-99]</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
</table>
<P></P>
<P></P>
You can also index arrays with a pair of numbers, <code>[start, count]</code>.
This returns a new array consisting of references to <code>count</code> objects
starting at position <code>start</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = [ 1, 3, 5, 7, 9 ]</code></td>
</tr>
<tr>
<td valign="top"><code>a[1, 3]</code></td>
<td valign="top"></td>
<td valign="top"><code>[3, 5, 7]</code></td>
</tr>
<tr>
<td valign="top"><code>a[3, 1]</code></td>
<td valign="top"></td>
<td valign="top"><code>[7]</code></td>
</tr>
<tr>
<td valign="top"><code>a[-3, 2]</code></td>
<td valign="top"></td>
<td valign="top"><code>[5, 7]</code></td>
</tr>
</table>
<P></P>
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = [ 1, 3, 5, 7, 9 ]</code></td>
</tr>
<tr>
<td valign="top"><code>a[1..3]</code></td>
<td valign="top"></td>
<td valign="top"><code>[3, 5, 7]</code></td>
</tr>
<tr>
<td valign="top"><code>a[1...3]</code></td>
<td valign="top"></td>
<td valign="top"><code>[3, 5]</code></td>
</tr>
<tr>
<td valign="top"><code>a[3..3]</code></td>
<td valign="top"></td>
<td valign="top"><code>[7]</code></td>
</tr>
<tr>
<td valign="top"><code>a[-3..-1]</code></td>
<td valign="top"></td>
<td valign="top"><code>[5, 7, 9]</code></td>
</tr>
</table>
<P></P>
<P></P>
The <code>[]</code> operator has a corresponding <code>[]=</code> 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 <code>nil</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr>
<td valign="top">a = [ 1, 3, 5, 7, 9 ]</td>
<td valign="top"></td>
<td valign="top">[1, 3, 5, 7, 9]</td>
</tr>
<tr>
<td valign="top">a[1] = 'bat'</td>
<td valign="top"></td>
<td valign="top">[1, "bat", 5, 7, 9]</td>
</tr>
<tr>
<td valign="top">a[-3] = 'cat'</td>
<td valign="top"></td>
<td valign="top">[1, "bat", "cat", 7, 9]</td>
</tr>
<tr>
<td valign="top">a[3] = [ 9, 8 ]</td>
<td valign="top"></td>
<td valign="top">[1, "bat", "cat", [9, 8], 9]</td>
</tr>
<tr>
<td valign="top">a[6] = 99</td>
<td valign="top"></td>
<td valign="top">[1, "bat", "cat", [9, 8], 9, nil, 99]</td>
</tr>
</table>
<P></P>
<P></P>
If the index to <code>[]=</code> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr>
<td valign="top">a = [ 1, 3, 5, 7, 9 ]</td>
<td valign="top"></td>
<td valign="top">[1, 3, 5, 7, 9]</td>
</tr>
<tr>
<td valign="top">a[2, 2] = 'cat'</td>
<td valign="top"></td>
<td valign="top">[1, 3, "cat", 9]</td>
</tr>
<tr>
<td valign="top">a[2, 0] = 'dog'</td>
<td valign="top"></td>
<td valign="top">[1, 3, "dog", "cat", 9]</td>
</tr>
<tr>
<td valign="top">a[1, 1] = [ 9, 8, 7 ]</td>
<td valign="top"></td>
<td valign="top">[1, 9, 8, 7, "dog", "cat", 9]</td>
</tr>
<tr>
<td valign="top">a[0..3] = []</td>
<td valign="top"></td>
<td valign="top">["dog", "cat", 9]</td>
</tr>
<tr>
<td valign="top">a[5] = 99</td>
<td valign="top"></td>
<td valign="top">["dog", "cat", 9, nil, nil, 99]</td>
</tr>
</table>
<P></P>
<P></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.
<h3>Hashes</h3>
<P></P>
Hashes (sometimes known as associative arrays or dictionaries) are
similar to arrays, in that they are indexed collectives of object
references.
<P></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> <code>=></code> <em>value</em> pairs between braces.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>h.length</code></td>
<td valign="top"></td>
<td valign="top"><code>3</code></td>
</tr>
<tr>
<td valign="top"><code>h['dog']</code></td>
<td valign="top"></td>
<td valign="top"><code>"canine"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>h['cow'] = 'bovine'</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>h[12] = 'dodecine'</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>h['cat'] = 99</code></td>
</tr>
<tr>
<td valign="top"><code>h</code></td>
<td valign="top"></td>
<td valign="top"><code>{"cow"=>"bovine", 12=>"dodecine", "dog"=>"canine", "donkey"=>"asinine", "cat"=>99}</code></td>
</tr>
</table>
<P></P>
<P></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></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
<code>Hash</code> starts on page 321.
<h3>Implementing a SongList Container</h3>
<P></P>
After that little diversion into arrays and hashes, we're now ready to
implement the jukebox's <code>SongList</code>. Let's invent a basic list of
methods we need in our <code>SongList</code>. We'll want to add to it as we go
along, but it will do for now.
<P></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 <i>anIndex</i>, which may be an
integer index or a song title.
</dd></dl>
<P></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 <code>Array</code>. Similarly, the ability to return a song at an integer
position in the list is supported by arrays.
<P></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></P>
We'll start our class with a basic <code>initialize</code> method, which
creates the <code>Array</code> we'll use to hold the songs and stores a
reference to it in the instance variable <code>@songs</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def initialize
@songs = Array.new
end
end
</pre></td></tr></table>
<P></P>
The <code>SongList#append</code> method adds the given song to the end of the
<code>@songs</code> array. It also returns <i>self</i>, a reference to the
current <code>SongList</code> object. This is a useful convention, as it lets
us chain together multiple calls to <code>append</code>. We'll see an
example of this later.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def append(aSong)
@songs.push(aSong)
self
end
end
</pre></td></tr></table>
<P></P>
Then we'll add the <code>deleteFirst</code> and <code>deleteLast</code>
methods, trivially implemented using <a href="ref_c_array.html#shift"><code>Array#shift</code></a> and
<a href="ref_c_array.html#pop"><code>Array#pop</code></a>, respectively.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def deleteFirst
@songs.shift
end
def deleteLast
@songs.pop
end
end
</pre></td></tr></table>
<P></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
<code>append</code> returns the <code>SongList</code> object to chain together
these method calls.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
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))
</pre></td></tr></table>
<P></P>
Then we'll check that songs are taken from the start and end of the
list correctly, and that <code>nil</code> is returned when the list becomes
empty.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>list.deleteFirst</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title1--artist1 (1)</code></td>
</tr>
<tr>
<td valign="top"><code>list.deleteFirst</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title2--artist2 (2)</code></td>
</tr>
<tr>
<td valign="top"><code>list.deleteLast</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title4--artist4 (4)</code></td>
</tr>
<tr>
<td valign="top"><code>list.deleteLast</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title3--artist3 (3)</code></td>
</tr>
<tr>
<td valign="top"><code>list.deleteLast</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
</table>
<P></P>
<P></P>
So far so good. Our next method is <code>[]</code>, which accesses elements
by index. If the index is a number (which we check using
<a href="ref_c_object.html#kind_of_qm"><code>Object#kind_of?</code></a>), we just return the
element at that position.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def [](key)
if key.kind_of?(Integer)
@songs[key]
else
# ...
end
end
end
</pre></td></tr></table>
<P></P>
Again, testing this is pretty trivial.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>list[0]</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title1--artist1 (1)</code></td>
</tr>
<tr>
<td valign="top"><code>list[2]</code></td>
<td valign="top"></td>
<td valign="top"><code>Song: title3--artist3 (3)</code></td>
</tr>
<tr>
<td valign="top"><code>list[9]</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
</table>
<P></P>
<P></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.<h2>Blocks and Iterators</h2>
<P></P>
So, our next problem with <code>SongList</code> is to implement the code in
method <code>[]</code> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
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
end
</pre></td></tr></table>
<P></P>
This works, and it looks comfortingly familiar: a <code>for</code> loop
iterating over an array. What could be more natural?
<P></P>
It turns out there <em>is</em> something more natural. In a way,
our <code>for</code> 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 <code>find</code> method in <code>Array</code> does.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def [](key)
if key.kind_of?(Integer)
result = @songs[key]
else
result = @songs.find { |aSong| key == aSong.name }
end
return result
end
end
</pre></td></tr></table>
<P></P>
We could use <code>if</code> as a statement modifier to shorten the
code even more.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def [](key)
return @songs[key] if key.kind_of?(Integer)
return @songs.find { |aSong| aSong.name == key }
end
end
</pre></td></tr></table>
<P></P>
The method <code>find</code> 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 <code>[]</code> method actually does).
<h3>Implementing Iterators</h3>
<P></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></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></P>
Within the method, the block may be invoked, almost as if it were a
method itself, using the <code>yield</code> statement.
Whenever a <code>yield</code>
is executed, it invokes the code in the block. When the block
exits, control picks back up immediately after the
<code>yield</code>.<em>[Programming-language buffs will be pleased to
know that the keyword <code>yield</code> was chosen to echo the <code>yield</code>
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.]</em> Let's start with a trivial example.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def threeTimes
yield
yield
yield
end
threeTimes { puts "Hello" }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Hello
Hello
Hello
</pre></td></tr></table>
<P></P>
The block (the code between the braces) is associated with the call to
the method <code>threeTimes</code>. Within this method, <code>yield</code> 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.<em>[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.]</em>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
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, " " }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
</pre></td></tr></table>
<P></P>
In this example, the <code>yield</code> 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 <code>f</code> receives the value passed to the <code>yield</code>, 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 <code>yield</code>
are converted to an array if the block has just one argument).
<P></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.<em>[For more information on this
and other ``gotchas,'' see the list beginning
on page 129; more performance information begins
on page 130.]</em>
<P></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 <code>yield</code>. This is how the <code>find</code> method used by class
<code>Array</code> works.<em>[The <code>find</code> method is actually defined
in module <code>Enumerable</code>, which is mixed into class <code>Array</code>.]</em> Its
implementation would look something like the following.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Array</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def find</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> for i in 0...size</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> value = self[i]</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> return value if yield(value)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> return nil</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>[1, 3, 5, 7, 9].find {|v| v*v > 30 }</code></td>
<td valign="top"></td>
<td valign="top"><code>7</code></td>
</tr>
</table>
<P></P>
<P></P>
This passes successive elements of the array to the associated block. If
the block returns <code>true</code>, the method returns the corresponding
element. If no element matches, the method returns <code>nil</code>. The example shows
the benefit of this approach to iterators. The <code>Array</code> 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></P>
Some iterators are common to many types of Ruby collections. We've
looked at <code>find</code> already. Two others are <code>each</code> and
<code>collect</code>.
<code>each</code> is probably the simplest iterator---all it does is yield
successive elements of its collection.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
[ 1, 3, 5 ].each { |i| puts i }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
1
3
5
<P></P>
</pre></td></tr></table>
<P></P>
The <code>each</code> iterator has a special place in Ruby;
on page
87 we'll describe how it's used as the basis of the
language's <code>for</code> loop, and starting on page 104 we'll see how
defining an <code>each</code> method can add a whole lot more
functionality to your class for free.
<P></P>
Another common iterator is <code>collect</code>, 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>["H", "A", "L"].collect { |x| x.succ }</code></td>
<td valign="top"></td>
<td valign="top"><code>["I", "B", "M"]</code></td>
</tr>
</table>
<P></P>
<h3>Ruby Compared with C++ and Java</h3>
<P></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 <code>yield</code>
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></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
f = File.open("testfile")
f.each do |line|
print line
end
f.close
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
This is line one
This is line two
This is line three
And so on...
</pre></td></tr></table>
<P></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 <code>inject</code> function.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
sumOfValues "Smalltalk method"
^self values
inject: 0
into: [ :sum :element | sum + element value]
</pre></td></tr></table>
<P></P>
<code>inject</code> works like this. The first time the associated block
is called, <code>sum</code> is set to <code>inject</code>'s parameter (zero in this case),
and <code>element</code> is set to the first element in the array. The second
and subsequent times the block is called, <code>sum</code> is set to the
value returned by the block on the previous call. This way, <code>sum</code>
can be used to keep a running total. The final value of <code>inject</code> is the
value returned by the block the last time it was called.
<P></P>
Ruby does not have an <code>inject</code> method, but
it's easy to write one. In this case we'll add it to the <code>Array</code>
class, while on page 102 we'll see how to make it more
generally available.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Array</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def inject(n)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> each { |value| n = yield(n, value) }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> n</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def sum</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> inject(0) { |n, value| n + value }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def product</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> inject(1) { |n, value| n * value }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td valign="top"><code>[ 1, 2, 3, 4, 5 ].sum</code></td>
<td valign="top"></td>
<td valign="top"><code>15</code></td>
</tr>
<tr>
<td valign="top"><code>[ 1, 2, 3, 4, 5 ].product</code></td>
<td valign="top"></td>
<td valign="top"><code>120</code></td>
</tr>
</table>
<P></P>
<P></P>
Although blocks are often the target of an iterator, they also have
other uses. Let's look at a few.
<h3>Blocks for Transactions</h3>
<P></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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class File
def File.openAndProcess(*args)
f = File.open(*args)
yield f
f.close()
end
end
<P></P>
File.openAndProcess("testfile", "r") do |aFile|
print while aFile.gets
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
This is line one
This is line two
This is line three
And so on...
</pre></td></tr></table>
<P></P>
This small example illustrates a number of techniques. The
<code>openAndProcess</code> method is a <em>class method</em>---it may be
called independent of any particular <code>File</code> object. We want it to
take the same arguments as the conventional <a href="ref_c_file.html#open"><code>File::open</code></a> method,
but we don't really care what those arguments are. Instead, we
specified the arguments as <code>*args</code>, meaning ``collect the actual
parameters passed to the method into an array.'' We then call
<code>File.open</code>, passing it <code>*args</code> as a parameter. This expands the
array back into individual parameters. The net result is that
<code>openAndProcess</code> transparently passes whatever parameters it
received to <a href="ref_c_file.html#open"><code>File::open</code></a>.
<P></P>
Once the file has been opened, <code>openAndProcess</code> calls <code>yield</code>,
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></P>
Finally, this example uses <code>do</code>...<code>end</code> to define a block. The only
difference between this notation and using braces to define blocks is
precedence: <code>do</code>...<code>end</code> binds lower than ``{...}''. We
discuss the impact of this on page 236.
<P></P>
The technique of having files manage their own lifecycle is so useful
that the class <code>File</code> supplied with Ruby supports it directly. If
<a href="ref_c_file.html#open"><code>File::open</code></a> 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 <a href="ref_c_file.html#open"><code>File::open</code></a> 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
<a href="ref_m_kernel.html#block_given_qm"><code>Kernel::block_given?</code></a>, which returns <code>true</code> if a block is associated
with the current method. Using it, you could implement <a href="ref_c_file.html#open"><code>File::open</code></a>
(again, ignoring error handling) using something like the following.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
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
</pre></td></tr></table>
<h3>Blocks Can Be Closures</h3>
<P></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 <font size="-2">STOP</font> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
bStart = Button.new("Start")
bPause = Button.new("Pause")
# ...
</pre></td></tr></table>
<P></P>
What happens when the user presses one of our buttons? In the
<code>Button</code> class, the hardware folks rigged things so that a
callback method, <code>buttonPressed</code>, will be invoked.
The obvious way of adding functionality to these buttons is to create
subclasses of <code>Button</code> and have each subclass implement its own
<code>buttonPressed</code> method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class StartButton < Button
def initialize
super("Start") # invoke Button's initialize
end
def buttonPressed
# do start actions...
end
end
<P></P>
bStart = StartButton.new
</pre></td></tr></table>
<P></P>
There are two problems here. First, this will lead to a large number
of subclasses. If the interface to <code>Button</code> 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></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class JukeboxButton < Button
def initialize(label, &action)
super(label)
@action = action
end
def buttonPressed
@action.call(self)
end
end
<P></P>
bStart = JukeboxButton.new("Start") { songList.start }
bPause = JukeboxButton.new("Pause") { songList.pause }
</pre></td></tr></table>
<P></P>
The key to all this is the second parameter to
<code>JukeboxButton#initialize</code>. If the last parameter in a method
definition is prefixed with an ampersand (such as <code>&action</code>),
Ruby
looks for a code block whenever that method is called. That code block
is converted to an object of class <code>Proc</code> 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 <code>@action</code>.
When the callback method <code>buttonPressed</code> is invoked, we use the
<a href="ref_c_proc.html#call"><code>Proc#call</code></a> method on that object to invoke the block.
<P></P>
So what exactly do we have when we create a <code>Proc</code> object? The
interesting thing is that it's more than just a chunk of code.
Associated with a block (and hence a <code>Proc</code> object) is all the
context in which the block was <em>defined</em>: the value of
<code>self</code>, 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></P>
Let's look at a contrived example. This example uses the method
<code>proc</code>,
which converts a block to a <code>Proc</code> object.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def nTimes(aThing)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> return proc { |n| aThing * n }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>p1 = nTimes(23)</code></td>
</tr>
<tr>
<td valign="top"><code>p1.call(3)</code></td>
<td valign="top"></td>
<td valign="top"><code>69</code></td>
</tr>
<tr>
<td valign="top"><code>p1.call(4)</code></td>
<td valign="top"></td>
<td valign="top"><code>92</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>p2 = nTimes("Hello ")</code></td>
</tr>
<tr>
<td valign="top"><code>p2.call(3)</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hello Hello Hello "</code></td>
</tr>
</table>
<P></P>
<P></P>
The method <code>nTimes</code> returns a <code>Proc</code> object that references
the method's parameter, <code>aThing</code>. Even though that parameter is out
of scope by the time the block is called, the parameter remains
accessible to the block.
<P></P>
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="tut_classes.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_stdtypes.html">Next ></a><br></td></tr></table><p></p><font size="-1">Extracted from the book "Programming Ruby -
The Pragmatic Programmer's Guide"</font><br><font size="-3">
Copyright
©
2000 Addison Wesley Longman, Inc. Released under the terms of the
<a href="http://www.opencontent.org/openpub/">Open Publication License</a> V1.0.
<br>
This reference is available for
<a href="http://www.pragmaticprogrammer.com/ruby/downloads/book.html">download</a>.
</font></body></html>
|