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
|
<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="intro.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_containers.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>Classes, Objects, and Variables</h1><hr><br>
<P></P>
From the examples we've shown so far, you might be wondering about our
earlier assertion that Ruby is an object-oriented language. Well,
this chapter is where we justify that claim. We're going to be looking
at how you create classes and objects in Ruby, and at some of the ways
in which Ruby is more powerful than most object-oriented languages.
Along the way, we'll be implementing part of our next billion-dollar
product, the Internet Enabled Jazz and Blue Grass jukebox.
<P></P>
After months of work, our highly paid Research and Development folks
have determined that our jukebox needs <em>songs</em>. So it seems like
a good idea to start off by setting up a Ruby class that represents
things that are songs. We know that a real song has a name, an artist, and
a duration, so we'll want to make sure that the song objects in our
program do, too.
<P></P>
We'll start off by creating a basic class <code>Song</code>,<em>[As we
mentioned on page 9, class names start with an
uppercase letter, while method names start with a lowercase letter.]</em>
which contains just a single method, <code>initialize</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Song
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
end
</pre></td></tr></table>
<P></P>
<code>initialize</code> is a special method in Ruby programs. When you
call <code>Song#new</code> to create a new <code>Song</code> object, Ruby creates an
uninitialized object and then calls that object's <code>initialize</code>
method, passing in any parameters that were passed to
<code>new</code>. This gives you a chance to write code that sets up your
object's state.
<P></P>
For class <code>Song</code>, the <code>initialize</code> method takes three
parameters. These parameters act just like local variables within the
method, so they follow the local variable naming convention of
starting with a lowercase letter.
<P></P>
Each object represents its own song, so we need each of our <code>Song</code>
objects to carry around its own song name, artist, and duration. This
means we need to store these values as <em>instance variables</em>
within the object.
In Ruby, an instance variable is simply a name
preceded by an ``at'' sign (``@''). In our example, the parameter
<code>name</code> is assigned to the instance variable <code>@name</code>,
<code>artist</code> is assigned to <code>@artist</code>, and <code>duration</code> (the
length of the song in seconds) is assigned to <code>@duration</code>.
<P></P>
Let's test our spiffy new class.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.inspect</code></td>
<td valign="top"></td>
<td valign="top"><code>"#<Song:0x4018bfc4 @duration=260, @artist=\"Fleck\", @name=\"Bicylops\">"</code></td>
</tr>
</table>
<P></P>
<P></P>
Well, it seems to work. By default, the <code>inspect</code> message,
which can be sent to any object, dumps out the object's id and instance
variables. It looks as though we have them set up correctly.
<P></P>
Our experience tells us that during development we'll be printing out
the contents of a <code>Song</code> object many times, and <code>inspect</code>'s
default formatting leaves something to be desired. Fortunately, Ruby
has a standard message, <code>to_s</code>,
which it
sends to any object it wants to render as a string. Let's try it on
our song.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"#<Song:0x4018c1b8>"</code></td>
</tr>
</table>
<P></P>
<P></P>
That wasn't too useful---it just reported the object id. So, let's
override <code>to_s</code> in our class.
As we do this, we should also take a moment to talk about how we're
showing the class definitions in this book.
<P></P>
In Ruby, classes are never closed: you can always add methods to an
existing class.
This applies to the classes you write as well as the
standard, built-in classes. All you have to do is open up a class
definition for an existing class, and the new contents you specify
will be added to whatever's there.
<P></P>
This is great for our purposes. As we go through this chapter, adding
features to our classes, we'll show just the class definitions for the
new methods; the old ones will still be there. It saves us having to
repeat redundant stuff in each example. Obviously, though, if you were
creating this code from scratch, you'd probably just throw all the
methods into a single class definition.
<P></P>
Enough detail! Let's get back to adding a <code>to_s</code> method to our
<code>Song</code> class.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "Song: #{@name}--#{@artist} (#{@duration})"</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>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"Song: Bicylops--Fleck (260)"</code></td>
</tr>
</table>
<P></P>
<P></P>
Excellent, we're making progress. However, we've slipped in something
subtle. We said that Ruby supports <code>to_s</code> for all objects, but
we didn't say how. The answer has to do with inheritance, subclassing,
and how Ruby determines what method to run when you send a message to
an object. This is a subject for a new section, so....
<h2>Inheritance and Messages</h2>
<P></P>
Inheritance allows you to create a class that is a refinement or
specialization of another class.
For example, our jukebox has the
concept of songs, which we encapsulate in class <code>Song</code>. Then
marketing comes along and tells us that we need to provide karaoke
support. A karaoke song is just like any other (there's no vocal on
it, but that doesn't concern us). However, it also has an associated
set of lyrics, along with timing information. When our jukebox plays a
karaoke song, the lyrics should flow across the screen on the front of
the jukebox in time with the music.
<P></P>
An approach to this problem is to define a new class, <code>KaraokeSong</code>,
which is just like <code>Song</code>, but with a lyric track.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class KaraokeSong < Song
def initialize(name, artist, duration, lyrics)
super(name, artist, duration)
@lyrics = lyrics
end
end
</pre></td></tr></table>
<P></P>
The ``<code>< Song</code>'' on the class definition line tells Ruby that a
<code>KaraokeSong</code> is a <em>subclass</em> of <code>Song</code>.
(Not surprisingly,
this means that <code>Song</code> is a <em>superclass</em> of <code>KaraokeSong</code>. People
also talk about parent-child relationships, so <code>KaraokeSong</code>'s
parent would be <code>Song</code>.) For now, don't worry too much about the
<code>initialize</code> method; we'll talk about that <code>super</code> call later.
<P></P>
Let's create a <code>KaraokeSong</code> and check that our code worked. (In the
final system, the lyrics will be held in an object that includes the
text and timing information. To test out our class, though, we'll just
use a string. This is another benefit of untyped languages---we don't
have to define everything before we start running code.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"Song: My Way--Sinatra (225)"</code></td>
</tr>
</table>
<P></P>
<P></P>
Well, it ran, but why doesn't the <code>to_s</code> method show the
lyric?
<P></P>
The answer has to do with the way Ruby determines which method should
be called when you send a message to an object. When Ruby compiles the
method invocation <code>aSong.to_s</code>, it doesn't actually know where to
find the method <code>to_s</code>. Instead, it defers the decision until
the program is run. At that time, it looks at the class of <code>aSong</code>.
If that class implements a method with the same name as the message,
that method is run. Otherwise, Ruby looks for a method in the parent
class, and then in the grandparent, and so on up the ancestor chain.
If it runs out of ancestors without finding the appropriate method, it
takes a special action that normally results in an error being
raised.<em>[In fact, you can intercept this error, which allows
you to fake out methods at runtime. This is described under
<a href="ref_c_object.html#method_missing"><code>Object#method_missing</code></a> on page 360.]</em>
<P></P>
So, back to our example. We sent the message <code>to_s</code> to
<code>aSong</code>, an object of class <code>KaraokeSong</code>.
Ruby looks in
<code>KaraokeSong</code> for a method called <code>to_s</code>, but doesn't find
it. The interpreter then looks in <code>KaraokeSong</code>'s parent, class
<code>Song</code>, and there it finds the <code>to_s</code> method that we defined
on page 20. That's why it prints out the song details but
not the lyrics---class <code>Song</code> doesn't know anything about lyrics.
<P></P>
Let's fix this by implementing <code>KaraokeSong#to_s</code>. There are a
number of ways to do this. Let's start with a bad way. We'll copy
the <code>to_s</code> method from <code>Song</code> and add on the lyric.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class KaraokeSong</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> # ...</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "KS: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}]"</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>aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"KS: My Way--Sinatra (225) [And now, the...]"</code></td>
</tr>
</table>
<P></P>
<P></P>
We're correctly displaying the value of the <code>@lyrics</code> instance
variable. To do this, the subclass directly accesses the instance
variables of its ancestors. So why is this a bad way to implement
<code>to_s</code>?
<P></P>
The answer has to do with good programming style (and something called
<em>decoupling</em>). By poking around in our parent's internal state,
we're tying ourselves tightly to its implementation. Say we decided to
change <code>Song</code> to store the duration in milliseconds. Suddenly,
<code>KaraokeSong</code> would start reporting ridiculous values. The idea of a
karaoke version of ``My Way'' that lasts for 3750 minutes is just too
frightening to consider.
<P></P>
We get around this problem by having each class handle its own
internal state. When <code>KaraokeSong#to_s</code> is called, we'll have it call
its parent's <code>to_s</code> method to get the song details. It will
then append to this the lyric information and return the result. The
trick here is the Ruby keyword ``<code>super</code>''. When you invoke
<code>super</code> with no arguments, Ruby sends a message to the current
object's parent, asking it to invoke a method of the same name as the
current method, and passing it the parameters that were passed to the
current method. Now we can implement our new and improved
<code>to_s</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class KaraokeSong < Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> # Format ourselves as a string by appending</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> # our lyrics to our parent's #to_s value.</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> super + " [#{@lyrics}]"</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>aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"Song: My Way--Sinatra (225) [And now, the...]"</code></td>
</tr>
</table>
<P></P>
<P></P>
We explicitly told Ruby that <code>KaraokeSong</code> was a subclass of
<code>Song</code>, but we didn't specify a parent class for <code>Song</code> itself. If
you don't specify a parent when defining a class, Ruby supplies
class <code>Object</code> as a default. This means that all objects have
<code>Object</code> as an ancestor, and that <code>Object</code>'s instance methods are
available to every object in Ruby. Back on page 20 we said
that <code>to_s</code> is available to all objects. Now we know why;
<code>to_s</code> is one of more than 35 instance methods in
class <code>Object</code>. The complete list begins on page 356.
<h3>Inheritance and Mixins</h3>
<P></P>
Some object-oriented languages (notably C++) support
multiple inheritance, where a class can have more than one immediate
parent, inheriting functionality from each. Although powerful, this
technique can be dangerous, as the inheritance hierarchy can
become ambiguous.
<P></P>
Other languages, such as Java, support single inheritance. Here, a
class can have only one immediate parent. Although cleaner (and easier
to implement), single inheritance also has drawbacks---in the real
world things often inherit attributes from multiple sources (a ball is
both a <em>bouncing thing</em> and a <em>spherical thing</em>, for
example).
<P></P>
Ruby offers an interesting and powerful compromise, giving you the
simplicity of single inheritance and the power of multiple
inheritance. A Ruby class can
have only one direct parent, and so Ruby is a single-inheritance
language. However, Ruby classes can include the functionality of any
number of mixins (a mixin is like a partial class definition). This
provides a controlled multiple-inheritance-like capability with none
of the drawbacks. We'll explore mixins more beginning
on page 100.
<P></P>
So far in this chapter we've been looking at classes and their
methods. Now it's time to move on to the objects, such as the
instances of class <code>Song</code>.
<h2>Objects and Attributes</h2>
<P></P>
The <code>Song</code> objects we've created so far have an internal state (such as
the song title and artist). That state is private to those
objects---no other object can access an object's instance variables.
In general, this is a Good Thing. It means that the object is solely
responsible for maintaining its own consistency.
<P></P>
However, an object that is totally secretive is pretty useless---you
can create it, but then you can't do anything with it. You'll normally
define methods that let you access and manipulate the state of an
object, allowing the outside world to interact with the object. These
externally visible facets of an object are called its
<em>attributes</em>.
<P></P>
For our <code>Song</code> objects, the first thing we may need is the ability
to find out the title and artist (so we can display them while the
song is playing) and the duration (so we can display some kind of
progress bar).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def name</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @name</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def artist</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @artist</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def duration</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @duration</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>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.artist</code></td>
<td valign="top"></td>
<td valign="top"><code>"Fleck"</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.name</code></td>
<td valign="top"></td>
<td valign="top"><code>"Bicylops"</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.duration</code></td>
<td valign="top"></td>
<td valign="top"><code>260</code></td>
</tr>
</table>
<P></P>
<P></P>
Here we've defined three accessor methods to return the values of the
three instance attributes. Because this is such a common idiom, Ruby
provides a convenient shortcut: <code>attr_reader</code> creates these
accessor methods for you.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> attr_reader :name, :artist, :duration</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.artist</code></td>
<td valign="top"></td>
<td valign="top"><code>"Fleck"</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.name</code></td>
<td valign="top"></td>
<td valign="top"><code>"Bicylops"</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.duration</code></td>
<td valign="top"></td>
<td valign="top"><code>260</code></td>
</tr>
</table>
<P></P>
<P></P>
This example has introduced something new. The construct <code>:artist</code>
is an expression that returns a <code>Symbol</code> object corresponding to
<code>artist</code>. You can think of <code>:artist</code> as meaning the <em>name</em>
of the variable <code>artist</code>, while plain <code>artist</code> is the
<em>value</em> of the variable. In this example, we named the accessor
methods <code>name</code>, <code>artist</code>, and <code>duration</code>. The
corresponding instance variables, <code>@name</code>, <code>@artist</code>, and
<code>@duration</code>, will be created automatically. These accessor methods
are identical to the ones we wrote by hand earlier.
<h3>Writable Attributes</h3>
<P></P>
Sometimes you need to be able to set an attribute from outside the
object. For example, let's assume that the duration that is initially
associated with a song is an estimate (perhaps gathered from
information on a CD or in the MP3 data). The first time we play the
song, we get to find out how long it actually is, and we store this
new value back in the <code>Song</code> object.
<P></P>
In languages such as C++ and Java, you'd do this with <em>setter
functions</em>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class JavaSong { // Java code
private Duration myDuration;
public void setDuration(Duration newDuration) {
myDuration = newDuration;
}
}
s = new Song(....)
s.setDuration(length)
</pre></td></tr></table>
<P></P>
In Ruby, the attributes of an object can be accessed as if they were
any other variable. We've seen this above with phrases such as
<code>aSong.name</code>. So, it seems natural to be able to assign to these
variables when you want to set the value of an attribute. In keeping
with the Principle of Least Surprise, that's just what you do in Ruby.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def duration=(newDuration)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @duration = newDuration</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>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.duration</code></td>
<td valign="top"></td>
<td valign="top"><code>260</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>aSong.duration = 257 # set attribute with updated value</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.duration</code></td>
<td valign="top"></td>
<td valign="top"><code>257</code></td>
</tr>
</table>
<P></P>
<P></P>
The assignment ``<code>aSong.duration = 257</code>'' invokes the method
<code>duration=</code> in the <code>aSong</code> object, passing it <code>257</code> as
an argument. In fact, defining a method name ending in an equals sign
makes that name eligible to appear on the left-hand side of an
assignment.
<P></P>
Again, Ruby provides a shortcut for creating these simple attribute
setting methods.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Song
attr_writer :duration
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration = 257
</pre></td></tr></table>
<h3>Virtual Attributes</h3>
<P></P>
These attribute accessing methods do not have to be just simple
wrappers around an object's instance variables. For example, you might
want to access the duration in minutes and fractions of a minute,
rather than in seconds as we've been doing.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Song</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def durationInMinutes</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @duration/60.0 # force floating point</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def durationInMinutes=(value)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> @duration = (value*60).to_i</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>aSong = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.durationInMinutes</code></td>
<td valign="top"></td>
<td valign="top"><code>4.333333333</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>aSong.durationInMinutes = 4.2</code></td>
</tr>
<tr>
<td valign="top"><code>aSong.duration</code></td>
<td valign="top"></td>
<td valign="top"><code>252</code></td>
</tr>
</table>
<P></P>
<P></P>
Here we've used attribute methods to create a virtual instance
variable. To the outside world, <code>durationInMinutes</code> seems to be an
attribute like any other. Internally, though, there is no
corresponding instance variable.
<P></P>
This is more than a curiosity. In his landmark book
<em>Object-Oriented Software Construction</em> ,
Bertrand Meyer
calls this the <em>Uniform Access Principle</em>.
By hiding the
difference between instance variables and calculated values, you are
shielding the rest of the world from the implementation of your class.
You're free to change how things work in the future without impacting
the millions of lines of code that use your class. This is a big win.
<h2>Class Variables and Class Methods</h2>
<P></P>
So far, all the classes we've created have contained instance
variables and instance methods: variables that are associated with a
particular instance of the class, and methods that work on those
variables. Sometimes classes themselves need to have their own states.
This is where class variables come in.
<h3>Class Variables</h3>
<P></P>
A class variable is shared among all objects of a class, and it is also
accessible to the class methods that we'll describe later.
There is
only one copy of a particular class variable for a given class. Class
variable names start with two ``at'' signs, such as ``<code>@@count</code>''.
Unlike global and instance variables, class variables must be
initialized before they are used. Often this initialization is just a
simple assignment in the body of the class definition.
<P></P>
For example, our jukebox may want to record how many times each
particular song has been played. This count would probably be an
instance variable of the <code>Song</code> object. When a song is played, the
value in the instance is incremented. But say we also want to know
how many songs have been played in total. We could do this by
searching for all the <code>Song</code> objects and adding up their counts, or
we could risk excommunication from the Church of Good Design and use a
global variable. Instead, we'll use a class variable.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Song
@@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
"This song: #@plays plays. Total #@@plays plays."
end
end
</pre></td></tr></table>
<P></P>
For debugging purposes, we've arranged for <code>Song#play</code> to return a
string containing the number of times this song has been played, along
with the total number of plays for all songs. We can test this easily.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>s1 = Song.new("Song1", "Artist1", 234) # test songs..</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>s2 = Song.new("Song2", "Artist2", 345)</code></td>
</tr>
<tr>
<td valign="top"><code>s1.play</code></td>
<td valign="top"></td>
<td valign="top"><code>"This song: 1 plays. Total 1 plays."</code></td>
</tr>
<tr>
<td valign="top"><code>s2.play</code></td>
<td valign="top"></td>
<td valign="top"><code>"This song: 1 plays. Total 2 plays."</code></td>
</tr>
<tr>
<td valign="top"><code>s1.play</code></td>
<td valign="top"></td>
<td valign="top"><code>"This song: 2 plays. Total 3 plays."</code></td>
</tr>
<tr>
<td valign="top"><code>s1.play</code></td>
<td valign="top"></td>
<td valign="top"><code>"This song: 3 plays. Total 4 plays."</code></td>
</tr>
</table>
<P></P>
<P></P>
Class variables are private to a class and its instances. If you want
to make them accessible to the outside world, you'll need to write an
accessor method. This method could be either an instance method or,
leading us neatly to the next section, a class method.
<h3>Class Methods</h3>
<P></P>
Sometimes a class needs to provide methods that work without being tied
to any particular object.
<P></P>
We've already come across one such method.
The <code>new</code> method creates a new <code>Song</code> object but is not
itself associated with a particular song.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
aSong = Song.new(....)
</pre></td></tr></table>
<P></P>
You'll find class methods sprinkled throughout the Ruby libraries. For
example, objects of class <code>File</code> represent open files
in the underlying file system. However, class <code>File</code> also provides
several class methods for manipulating files that aren't open and
therefore don't have a <code>File</code> object. If you want to delete a file,
you call the class method <a href="ref_c_file.html#delete"><code>File::delete</code></a>, passing in the name.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
File.delete("doomedFile")
</pre></td></tr></table>
<P></P>
Class methods are distinguished from instance methods by their
definition.
Class methods are defined by placing the class name and a period in
front of the method name.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Example
<P></P>
def instMeth # instance method
end
<P></P>
def Example.classMeth # class method
end
<P></P>
end
</pre></td></tr></table>
<P></P>
Jukeboxes charge money
for each song played, not by the minute. That makes short songs more
profitable than long ones. We may want to prevent songs that take too
long from being available on the SongList. We could define a class
method in <code>SongList</code> that checked to see if a particular song
exceeded the limit. We'll set this limit using a class constant, which
is simply a constant (remember constants? they start with an uppercase
letter) that is initialized in the class body.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class SongList</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> MaxTime = 5*60 # 5 minutes</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def SongList.isTooLong(aSong)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> return aSong.duration > MaxTime</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>song1 = Song.new("Bicylops", "Fleck", 260)</code></td>
</tr>
<tr>
<td valign="top"><code>SongList.isTooLong(song1)</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>song2 = Song.new("The Calling", "Santana", 468)</code></td>
</tr>
<tr>
<td valign="top"><code>SongList.isTooLong(song2)</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
</table>
<P></P>
<h3>Singletons and Other Constructors</h3>
<P></P>
Sometimes you want to override the default way in which Ruby creates
objects. As an example, let's look at our jukebox. Because we'll have
many jukeboxes, spread all over the country, we want to make
maintenance as easy as possible. Part of the requirement is to log
everything that happens to a jukebox: the songs that are played, the
money received, the strange fluids poured into it, and so on. Because
we want to reserve the network bandwidth for music, we'll store these
logfiles locally. This means we'll need a class that handles logging.
However, we want only one logging object per jukebox, and we want
that object to be shared among all the other objects that use it.
<P></P>
Enter the Singleton pattern, documented in <em>Design
Patterns</em> .
We'll arrange things so that the
only way to create a logging object is to call <code>Logger#create</code>,
and we'll ensure that only one logging object is ever created.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Logger
private_class_method :new
@@logger = nil
def Logger.create
@@logger = new unless @@logger
@@logger
end
end
</pre></td></tr></table>
<P></P>
By making <code>Logger</code>'s method <code>new</code> private, we prevent anyone from
creating a logging object using the conventional constructor. Instead, we provide a class method,
<code>Logger#create</code>. This uses the class variable <code>@@logger</code> to
keep a reference to a single instance of the logger, returning that
instance every time it is called.<em>[The implementation of
singletons that we present here is not thread-safe; if multiple
threads were running, it would be possible to create multiple logger
objects. Rather than add thread safety ourselves, however, we'd
probably use the <code>Singleton</code> mixin supplied with Ruby, which is
documented on page 472.]</em> We can check this by looking
at the object identifiers the method returns.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>Logger.create.id</code></td>
<td valign="top"></td>
<td valign="top"><code>537684700</code></td>
</tr>
<tr>
<td valign="top"><code>Logger.create.id</code></td>
<td valign="top"></td>
<td valign="top"><code>537684700</code></td>
</tr>
</table>
<P></P>
<P></P>
Using class methods as pseudo-constructors can also make life easier
for users of your class. As a trivial example, let's look at a class
<code>Shape</code> that represents a regular polygon. Instances of <code>Shape</code>
are created by giving the constructor the required number of sides and
the total perimeter.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Shape
def initialize(numSides, perimeter)
# ...
end
end
</pre></td></tr></table>
<P></P>
However, a couple of years later, this class is used in a different
application, where the programmers are used to creating shapes by
name, and by specifying the length of the side, not the
perimeter. Simply add some class methods to <code>Shape</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Shape
def Shape.triangle(sideLength)
Shape.new(3, sideLength*3)
end
def Shape.square(sideLength)
Shape.new(4, sideLength*4)
end
end
</pre></td></tr></table>
<P></P>
There are many interesting and powerful uses of class methods, but
exploring them won't get our jukebox finished any sooner, so let's
move on.
<h2>Access Control</h2>
<P></P>
When designing a class interface, it's important to consider just how
much access to your class you'll be exposing to the outside world.
Allow too much access into your class, and you risk increasing the
coupling in your application---users of your class will be tempted to
rely on details of your class's implementation, rather than on its
logical interface. The good news is that the only way to change an
object's state in Ruby is by calling one of its methods. Control
access to the methods and you've controlled access to the object.
A good rule of thumb is never to expose methods that could leave an
object in an invalid state. Ruby gives us three levels of protection.
<P></P>
<ul>
<li> <b>Public methods</b> can be called by anyone---there is no
access control. Methods are public by default (except for
<code>initialize</code>, which is always private).
</li><li> <b>Protected methods</b> can be invoked only by objects of the
defining class and its subclasses. Access is kept within the family.
</li><li> <b>Private methods</b> cannot be called with an explicit
receiver. Because you cannot specify an object when using them,
private methods can be called only in the defining class and by
direct descendents within that same object.
</li></ul>
<P></P>
The difference between ``protected'' and ``private'' is fairly subtle,
and is different in Ruby than in most common OO languages. If a method is
protected, it may be called by <em>any</em> instance of the defining
class or its subclasses. If a method is private, it may be called only
within the context of the calling object---it is never possible to
access another object's private methods directly, even if the object
is of the same class as the caller.
<P></P>
Ruby differs from other OO languages in another important way. Access
control is determined dynamically, as the program runs, not
statically. You will get an access violation only when the code
attempts to execute the restricted method.
<h3>Specifying Access Control</h3>
<P></P>
You specify access levels to methods within class or module
definitions using one or more of the three functions <code>public</code>,
<code>protected</code>, and <code>private</code>. Each function can be used in two
different ways.
<P></P>
If used with no arguments, the three functions set the default access
control of subsequently defined methods. This is probably familiar
behavior if you're a C++ or Java programmer, where you'd use keywords
such as <code>public</code> to achieve the same effect.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class MyClass
<P></P>
def method1 # default is 'public'
#...
end
<P></P>
protected # subsequent methods will be 'protected'
<P></P>
def method2 # will be 'protected'
#...
end
<P></P>
private # subsequent methods will be 'private'
<P></P>
def method3 # will be 'private'
#...
end
<P></P>
public # subsequent methods will be 'public'
<P></P>
def method4 # and this will be 'public'
#...
end
end
</pre></td></tr></table>
<P></P>
Alternatively, you can set access levels of named methods by listing
them as arguments to the access control functions.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class MyClass
<P></P>
def method1
end
<P></P>
# ... and so on
<P></P>
public :method1, :method4
protected :method2
private :method3
end
</pre></td></tr></table>
<P></P>
A class's <code>initialize</code> method is automatically declared
to be private.
<P></P>
It's time for some examples. Perhaps we're modeling an accounting
system where every debit has a corresponding credit. Because we want
to ensure that no one can break this rule, we'll make the methods that
do the debits and credits private, and we'll define our external
interface in terms of transactions.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Accounts
<P></P>
private
<P></P>
def debit(account, amount)
account.balance -= amount
end
def credit(account, amount)
account.balance += amount
end
<P></P>
public
<P></P>
#...
def transferToSavings(amount)
debit(@checking, amount)
credit(@savings, amount)
end
#...
end
</pre></td></tr></table>
<P></P>
Protected access is used when objects need to access the internal
state of other objects of the same class. For example, we may want to
allow the individual <code>Account</code> objects to compare their raw
balances, but may want to hide those balances from the rest of the
world (perhaps because we present them in a different form).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Account
attr_reader :balance # accessor method 'balance'
<P></P>
protected :balance # and make it protected
<P></P>
def greaterBalanceThan(other)
return @balance > other.balance
end
end
</pre></td></tr></table>
<P></P>
Because the attribute <code>balance</code> is protected, it's available
only within <code>Account</code> objects.
<h2>Variables</h2>
<P></P>
Now that we've gone to the trouble to create all these objects,
let's make sure we don't lose them. Variables are used to keep track
of objects; each variable holds a reference to an object.
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>Figure not available...</td></tr></table>
<P></P>
Let's confirm this with some code.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>person = "Tim"</code></td>
</tr>
<tr>
<td valign="top"><code>person.id</code></td>
<td valign="top"></td>
<td valign="top"><code>537684980</code></td>
</tr>
<tr>
<td valign="top"><code>person.type</code></td>
<td valign="top"></td>
<td valign="top"><code>String</code></td>
</tr>
<tr>
<td valign="top"><code>person</code></td>
<td valign="top"></td>
<td valign="top"><code>"Tim"</code></td>
</tr>
</table>
<P></P>
<P></P>
On the first line, Ruby creates a new <code>String</code> object with the
value ``Tim.'' A reference to this object is placed in the local
variable <code>person</code>.
A quick check shows that the variable has indeed taken on the
personality of a string, with an object id, a type, and a value.
<P></P>
So, is a variable an object?
<P></P>
In Ruby, the answer is ``no.'' A variable is simply a reference to an
object. Objects float around in a big pool somewhere (the heap, most
of the time) and are pointed to by variables.
<P></P>
Let's make the example slightly more complicated.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>person1 = "Tim"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>person2 = person1</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>person1[0] = 'J'</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>person1</code></td>
<td valign="top"></td>
<td valign="top"><code>"Jim"</code></td>
</tr>
<tr>
<td valign="top"><code>person2</code></td>
<td valign="top"></td>
<td valign="top"><code>"Jim"</code></td>
</tr>
</table>
<P></P>
<P></P>
What happened here? We changed the first character of
<code>person1</code>, but both <code>person1</code> and <code>person2</code>
changed from ``Tim'' to ``Jim.''
<P></P>
It all comes back to the fact that variables hold references to
objects, not the objects themselves. The assignment of <code>person1</code>
to <code>person2</code> doesn't create any new objects; it simply copies
<code>person1</code>'s object reference to <code>person2</code>, so that both
<code>person1</code> and <code>person2</code> refer to the same object. We show
this in Figure 3.1 on page 33.
<P></P>
Assignment <em>aliases</em> objects, potentially giving you multiple
variables that reference the same object.
But can't this cause problems in your code? It can, but not
as often as you'd think (objects in Java, for example, work exactly
the same way). For instance, in the example in Figure
3.1, you could avoid aliasing by using the <code>dup</code>
method of <code>String</code>, which creates a new <code>String</code> object with identical
contents.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>person1 = "Tim"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>person2 = person1.dup</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>person1[0] = "J"</code></td>
</tr>
<tr>
<td valign="top"><code>person1</code></td>
<td valign="top"></td>
<td valign="top"><code>"Jim"</code></td>
</tr>
<tr>
<td valign="top"><code>person2</code></td>
<td valign="top"></td>
<td valign="top"><code>"Tim"</code></td>
</tr>
</table>
<P></P>
<P></P>
You can also prevent anyone from changing a particular object by
freezing it (we talk more about freezing objects
on page 255). Attempt to alter a frozen object, and Ruby
will raise a <code>TypeError</code> exception.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
person1 = "Tim"
person2 = person1
person1.freeze # prevent modifications to the object
person2[0] = "J"
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
prog.rb:4:in `=': can't modify frozen string (TypeError)
from prog.rb:4
</pre></td></tr></table>
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="intro.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_containers.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>
|