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
|
<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="language.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="taint.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 and Objects</h1><hr><br>
<P></P>
Classes and objects are obviously central to Ruby, but at first sight
they can seem a little confusing. There seem to be a lot of concepts:
classes, objects, class objects, instance methods, class methods, and
singleton classes. In reality, however, Ruby has just a single
underlying class and object structure, which we'll discuss in this
chapter. In fact, the basic model is so simple, we can describe it in
a single paragraph.
<P></P>
A Ruby object has three components: a set of flags,
some instance variables, and an associated class. A Ruby class is an
object of class <code>Class</code>, which contains all the object things plus a
list of methods and a reference to a superclass (which is itself
another class). All method calls in Ruby nominate a receiver (which is
by default <code>self</code>, the current object).
Ruby finds the method to
invoke by looking at the list of methods in the receiver's class. If
it doesn't find the method there, it looks in the superclass, and then
in the superclass's
superclass, and so on. If the method cannot be found in the receiver's
class or any of its ancestors, Ruby invokes the method
<code>method_missing</code> on the original receiver.
<P></P>
And that's it---the entire explanation. On to the next chapter.
<P></P>
``But wait,'' you cry, ``I spent good money on this chapter. What
about all this other stuff---singleton classes, class methods, and so
on. How do they work?''
<P></P>
Good question.
<h2>How Classes and Objects Interact</h2>
<P></P>
All class/object interactions are explained using the simple model
given above: objects reference classes, and
classes reference zero or more superclasses. However, the
implementation details can get a tad tricky.
<P></P>
We've found that the simplest way of visualizing all this is to draw
the actual objects that Ruby implements. So, in the following pages
we'll look at all the possible combinations of classes and
objects. Note that these are not class diagrams in the UML sense;
we're showing structures in memory and pointers between them.
<h3>Your Basic, Everyday Object</h3>
<P></P>
Let's start by looking at an object created from a simple
class. Figure 19.1 on page 243 shows
an object referenced by a variable, <code>lucille</code>, the object's class,
<code>Guitar</code>, and that class's superclass, <code>Object</code>. Notice how the
object's class reference (called <code>klass</code> for historical reasons
that really bug Andy) points to the class object, and how the
<code>super</code> pointer from that class references the parent class.
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>Figure not available...</td></tr></table>
<P></P>
When Ruby executes <code>Guitar.strings()</code>, it follows the same process
as before: it goes to the receiver, class <code>Guitar</code>, follows the
<code>klass</code> reference to class <code>Guitar$'$</code>, and finds the method.
<P></P>
Finally, note that an ``S'' has crept into the flags in class
<code>Guitar$'$</code>. The classes that Ruby creates automatically are
marked internally as <em>singleton classes</em>.
Singleton classes are
treated slightly differently within Ruby. The most obvious difference
from the outside is that they are effectively invisible: they will
never appear in a list of objects returned from methods such as
<a href="ref_c_module.html#ancestors"><code>Module#ancestors</code></a> or <a href="ref_m_objectspace.html#each_object"><code>ObjectSpace::each_object</code></a>.
<h3>Object-Specific Classes</h3>
<P></P>
Ruby allows you to create a class tied to a particular object. In the
following example, we create two <code>String</code> objects. We then associate
an anonymous class with one of them,
overriding one of the methods in
the object's base class and adding a new method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "hello"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>b = a.dup</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>class <<a</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "The value is '#{self}'"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def twoTimes</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> self + self</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>a.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"The value is 'hello'"</code></td>
</tr>
<tr>
<td valign="top"><code>a.twoTimes</code></td>
<td valign="top"></td>
<td valign="top"><code>"hellohello"</code></td>
</tr>
<tr>
<td valign="top"><code>b.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"hello"</code></td>
</tr>
</table>
<P></P>
<P></P>
This example uses the ``<code>class <<</code><i>obj</i>'' notation, which
basically says ``build me a new class just for object <i>obj</i>.'' We
could also have written it as:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "hello"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>b = a.dup</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>def a.to_s</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "The value is '#{self}'"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>def a.twoTimes</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> self + self</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>a.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"The value is 'hello'"</code></td>
</tr>
<tr>
<td valign="top"><code>a.twoTimes</code></td>
<td valign="top"></td>
<td valign="top"><code>"hellohello"</code></td>
</tr>
<tr>
<td valign="top"><code>b.to_s</code></td>
<td valign="top"></td>
<td valign="top"><code>"hello"</code></td>
</tr>
</table>
<P></P>
<P></P>
The effect is the same in both cases: a class is added to the object
``<code>a</code>''. This gives us a strong hint about the Ruby implementation:
a singleton class is created and inserted as <code>a</code>'s direct
class. <code>a</code>'s original class, <code>String</code>, is made this singleton's
superclass. The before and after pictures are shown in Figure
19.3 on page 246.
<P></P>
Ruby performs a slight optimization with these singleton classes. If
an object's <code>klass</code> reference already points to a singleton class,
a new one will not be created. This means that the first of the two
method definitions in the previous example will create a singleton
class, but the second will simply add a method to it.
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>Figure not available...</td></tr></table>
<P></P>
<h3>Mixin Modules</h3>
<P></P>
When a class includes a module, that module's instance methods become
available as instance methods of the class. It's almost as if the
module becomes a superclass of the class that uses it. Not
surprisingly, that's about how it works. When you include a module,
Ruby creates an anonymous proxy class that references that module, and
inserts that proxy as the direct superclass of the class that did the
including. The proxy class contains references to the instance
variables and methods of the module. This is important: the same
module may be included in many different classes, and will appear in
many different inheritance chains. However, thanks to the proxy
class,
there is still only one underlying module: change a method definition
in that module, and it will change in all classes that include that
module, both past and future.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>module SillyModule</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def hello</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "Hello."</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>class SillyClass</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> include SillyModule</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>s = SillyClass.new</code></td>
</tr>
<tr>
<td valign="top"><code>s.hello</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hello."</code></td>
</tr>
</table>
<P></P>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>module SillyModule</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def hello</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "Hi, there!"</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>s.hello</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hi, there!"</code></td>
</tr>
</table>
<P></P>
<P></P>
The relationship between classes and the modules they include is shown
in Figure 19.4 on page 247. If multiple modules are included, they
are added to the chain in order.
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>Figure not available...</td></tr></table>
<P></P>
If a module itself includes other modules, a chain of proxy classes
will be added to any class that includes that module, one proxy for
each module that is directly or indirectly included.
<h3>Extending Objects</h3>
<P></P>
Just as you can define an anonymous class for an
object using ``<code>class <<<i>obj</i></code>'', you can mix a module into an
object using <a href="ref_c_object.html#extend"><code>Object#extend</code></a>. For example:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>module Humor</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def tickle</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "hee, hee!"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a = "Grouchy"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a.extend Humor</code></td>
</tr>
<tr>
<td valign="top"><code>a.tickle</code></td>
<td valign="top"></td>
<td valign="top"><code>"hee, hee!"</code></td>
</tr>
</table>
<P></P>
<P></P>
There is an interesting trick with <code>extend</code>.
If you use it
within a class definition, the module's methods become class
methods.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>module Humor</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def tickle</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "hee, hee!"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>class Grouchy</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> include Humor</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> extend Humor</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>Grouchy.tickle</code></td>
<td valign="top"></td>
<td valign="top"><code>"hee, hee!"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a = Grouchy.new</code></td>
</tr>
<tr>
<td valign="top"><code>a.tickle</code></td>
<td valign="top"></td>
<td valign="top"><code>"hee, hee!"</code></td>
</tr>
</table>
<P></P>
<P></P>
This is because calling <code>extend</code> is equivalent to
<code>self.extend</code>, so the methods are added to <code>self</code>, which in a
class definition is the class itself.
<h2>Class and Module Definitions</h2>
<P></P>
Having exhausted the combinations of classes and objects, we can
(thankfully) get back to programming by looking at the nuts and bolts
of class and module definitions.
<P></P>
In languages such as C++ and Java, class definitions are processed at
compile time: the compiler loads up symbol tables, works out how much
storage to allocate, constructs dispatch tables, and does all those other
obscure things we'd rather not think too hard about.
<P></P>
Ruby is different. In Ruby, class and module definitions are executable
code. Although parsed at compile time, the classes and modules are
created at runtime, when the definition is encountered. (The same is
also true of method definitions.) This allows you to structure your
programs far more dynamically than in most conventional languages.
You can make decisions once, when the class is being
defined, rather than each time that objects of the class are
used. The class in the following example decides as it is being
defined what version of a decryption routine to create.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class MediaPlayer
include Tracing if $DEBUGGING
<P></P>
if ::EXPORT_VERSION
def decrypt(stream)
raise "Decryption not available"
end
else
def decrypt(stream)
# ...
end
end
<P></P>
end
</pre></td></tr></table>
<P></P>
If class definitions are executable code, this implies that they
execute in the context of some object: <code>self</code> must reference
<em>something</em>. Let's find out what it is.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Test
puts "Type of self = #{self.type}"
puts "Name of self = #{self.name}"
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Type of self = Class
Name of self = Test
</pre></td></tr></table>
<P></P>
This means that a class definition is executed with that class as the
current object. Referring back to the section about metaclasses
on page 242, we can see that this means that methods in
the metaclass and its superclasses will be available during the
execution of the method definition. We can check this out.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Test
def Test.sayHello
puts "Hello from #{name}"
end
<P></P>
sayHello
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Hello from Test
</pre></td></tr></table>
<P></P>
In this example we define a class method, <code>Test#sayHello</code>, and
then call it in the body of the class definition. Within
<code>sayHello</code>, we call <code>name</code>, an instance method of class
<code>Module</code>. Because <code>Module</code> is an ancestor of <code>Class</code>, its instance
methods can be called without an explicit receiver within a class definition.
<P></P>
In fact, many of the directives that you use when defining a class
or module, things such as <code>alias_method</code>, <code>attr</code>, and
<code>public</code>, are simply methods in class <code>Module</code>. This opens up
some interesting possibilities---you can extend the functionality of
class and module definitions by writing Ruby code. Let's look at a
couple of examples.
<P></P>
As a first example, let's look at adding a basic documentation
facility to modules and classes.
This would allow us to associate a
string with modules and classes that we write, a string that is
accessible as the program is running. We'll choose a simple syntax.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Example
doc "This is a sample documentation string"
# .. rest of class
end
</pre></td></tr></table>
<P></P>
We need to make <code>doc</code> available to any module or class, so we
need to make it an instance method of class <code>Module</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Module
@@docs = Hash.new(nil)
def doc(str)
@@docs[self.name] = str
end
<P></P>
def Module::doc(aClass)
# If we're passed a class or module, convert to string
# ('<=' for classes checks for same class or subtype)
aClass = aClass.name if aClass.type <= Module
@@docs[aClass] || "No documentation for #{aClass}"
end
end
<P></P>
class Example
doc "This is a sample documentation string"
# .. rest of class
end
<P></P>
module Another
doc <<-edoc
And this is a documentation string
in a module
edoc
# rest of module
end
<P></P>
puts Module::doc(Example)
puts Module::doc("Another")
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
This is a sample documentation string
And this is a documentation string
in a module
</pre></td></tr></table>
<P></P>
The second example is a performance enhancement based on Tadayoshi Funaba's
<code>date</code> module
(described beginning on page 443). Say we
have a class that represents some underlying quantity (in this case, a
date). The class may have many attributes that present the same
underlying date in different ways: as a Julian day number, as a
string, as a [year, month, day] triple, and so on. Each value
represents the same date and may involve a fairly complex calculation
to derive. We therefore would like to calculate each attribute only
once, when it is first accessed.
<P></P>
The manual way would be to add a test to each accessor:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class ExampleDate
def initialize(dayNumber)
@dayNumber = dayNumber
end
<P></P>
def asDayNumber
@dayNumber
end
<P></P>
def asString
unless @string
# complex calculation
@string = result
end
@string
end
<P></P>
def asYMD
unless @ymd
# another calculation
@ymd = [ y, m, d ]
end
@ymd
end
# ...
end
</pre></td></tr></table>
<P></P>
This is a clunky technique---let's see if we can come up with
something sexier.
<P></P>
What we're aiming for is a directive that indicates that the body of a
particular method should be invoked only once. The value returned by
that first call should be cached. Thereafter, calling that same method
should return the cached value without reevaluating the method body
again. This is similar to Eiffel's <code>once</code> modifier for routines.
We'd like to be able to write something like:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class ExampleDate
def asDayNumber
@dayNumber
end
<P></P>
def asString
# complex calculation
end
<P></P>
def asYMD
# another calculation
[ y, m, d ]
end
<P></P>
once :asString, :asYMD
end
</pre></td></tr></table>
<P></P>
We can use <code>once</code> as a directive by writing it as a class method of
<code>ExampleDate</code>,
but what should it look like internally? The trick
is to have it rewrite the methods whose names it is passed. For each
method, it creates an alias for the original code, then creates a new
method with the same name. This new method does two things. First, it
invokes the original method (using the alias) and stores the resulting
value in an instance variable. Second, it redefines itself, so that on
subsequent calls it simply returns the value of the instance variable
directly. Here's Tadayoshi Funaba's code, slightly reformatted.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def ExampleDate.once(*ids)
for id in ids
module_eval <<-"end_eval"
alias_method :__#{id.to_i}__, #{id.inspect}
def #{id.id2name}(*args, &block)
def self.#{id.id2name}(*args, &block)
@__#{id.to_i}__
end
@__#{id.to_i}__ = __#{id.to_i}__(*args, &block)
end
end_eval
end
end
</pre></td></tr></table>
<P></P>
This code uses <code>module_eval</code> to execute a block of code in the context of
the calling module (or, in this case, the calling class). The original
method is renamed <em>__nnn__</em>, where the <em>nnn</em> part is
the integer representation of the method name's symbol id. The code
uses the same name for the caching instance variable. The bulk
of the code is a method that dynamically redefines itself. Note that
this redefinition uses the fact that methods may contain nested
singleton method definitions, a clever trick.
<P></P>
Understand this code, and you'll be well on the way to true Ruby mastery.
<P></P>
However, we can take it further. Look in the <code>date</code> module, and you'll
see method <code>once</code> written slightly differently.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Date
class << self
def once(*ids)
# ...
end
end
# ...
end
</pre></td></tr></table>
<P></P>
The interesting thing here is the inner class definition,
``<code>class << self</code>''. This defines a class based on the object
<code>self</code>, and <code>self</code> happens to be the class object for
<code>Date</code>. The result? Every method within the inner class definition
is automatically a class method of <code>Date</code>.
<P></P>
The <code>once</code> feature is generally
applicable---it should work for any class. If you took <code>once</code>
and made it a private instance method of class <code>Module</code>, it would be
available for use in any Ruby class.
<h3>Class Names Are Constants</h3>
<P></P>
We've said that when you invoke a class method, all you're doing is
sending a message to the <code>Class</code> object itself. When you say
something such as <code>String.new("gumby")</code>, you're sending the message
<code>new</code> to the object that is class <code>String</code>. But how does Ruby
know to do this? After all, the receiver of a message should be an
object reference, which implies that there must be a
constant called ``String'' somewhere containing a reference to the
<code>String</code> object.<em>[It will be a constant, not a variable,
because ``String'' starts with an uppercase letter.]</em>
And in fact, that's exactly what happens. All the built-in classes,
along with the classes you define, have a corresponding global
constant with the same name as the class.
This is both straightforward and subtle. The subtlety comes from the
fact that there are actually two things named (for example) <code>String</code> in the
system. There's a <em>constant</em> that references an object of class
<code>String</code>, and there's the object itself.
<P></P>
The fact that class names are just constants means that you can treat
classes just like any other Ruby object: you can copy them, pass them
to methods, and use them in expressions.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def factory(klass, *args)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> klass.new(*args)</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>factory(String, "Hello")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hello"</code></td>
</tr>
<tr>
<td valign="top"><code>factory(Dir, ".")</code></td>
<td valign="top"></td>
<td valign="top"><code>#<Dir:0x4018d1a8></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>flag = true</code></td>
</tr>
<tr>
<td valign="top"><code>(flag ? Array : Hash)[1, 2, 3, 4]</code></td>
<td valign="top"></td>
<td valign="top"><code>[1, 2, 3, 4]</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>flag = false</code></td>
</tr>
<tr>
<td valign="top"><code>(flag ? Array : Hash)[1, 2, 3, 4]</code></td>
<td valign="top"></td>
<td valign="top"><code>{1=>2, 3=>4}</code></td>
</tr>
</table>
<P></P>
<h2>Top-Level Execution Environment</h2>
<P></P>
Many times in this book we've claimed that everything in Ruby is an
object. However, there's one thing that we've used time and time again
that appears to contradict this---the top-level Ruby execution environment.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
puts "Hello, World"
</pre></td></tr></table>
<P></P>
Not an object in sight. We may as well be writing some variant of
Fortran or QW-Basic. But dig deeper, and you'll come across objects
and classes lurking in even the simplest code.
<P></P>
We know that the literal <code>"Hello, World"</code> generates a Ruby
<code>String</code>, so there's one object. We also know that the bare method
call to <code>puts</code> is effectively the same as <code>self.puts</code>. But
what is ``self''?
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>self.type</code></td>
<td valign="top"></td>
<td valign="top"><code>Object</code></td>
</tr>
</table>
<P></P>
<P></P>
At the top level, we're executing code in the context of some
predefined object. When we define methods, we're actually creating
(private) singleton methods for this object. Instance variables belong
to this object. And because we're in the context of <code>Object</code>, we can
use all of <code>Object</code>'s methods (including those mixed-in from <code>Kernel</code>)
in function form. This explains why we can call <code>Kernel</code> methods
such as <code>puts</code> at the top level (and indeed throughout Ruby):
these methods are part of every object.
<h2>Inheritance and Visibility</h2>
<P></P>
There's one last wrinkle to class inheritance, and it's fairly
obscure.
<P></P>
Within a class definition, you can change the visibility of a method
in an ancestor class. For example, you can do something like:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Base
def aMethod
puts "Got here"
end
private :aMethod
end
<P></P>
class Derived1 < Base
public :aMethod
end
<P></P>
class Derived2 < Base
end
</pre></td></tr></table>
<P></P>
In this example, you would be able to invoke <code>aMethod</code> in
instances of class <code>Derived1</code>, but not via instances of <code>Base</code> or
<code>Derived2</code>.
<P></P>
So how does Ruby pull off this feat of having one method
with two different visibilities? Simply put, it cheats.
<P></P>
If a subclass changes the visibility of a method in a parent, Ruby
effectively inserts a hidden proxy method in the subclass that invokes
the original method using <code>super</code>. It then sets the visibility
of that proxy to whatever you requested. This means that the code:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Derived1 < Base
public :aMethod
end
</pre></td></tr></table>
<P></P>
is effectively the same as:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Derived1 < Base
def aMethod(*args)
super
end
public :aMethod
end
</pre></td></tr></table>
<P></P>
The call to <code>super</code> can access the parent's method regardless of
its visibility, so the rewrite allows the subclass to override its
parent's visibility rules. Pretty scary, eh?
<h2>Freezing Objects</h2>
<P></P>
There are times when you've worked hard to make your object exactly
right, and you'll be damned if you'll let anyone just change
it. Perhaps you need to pass some kind of opaque object between two of
your classes via some third-party object, and you want to make sure it
arrives unmodified. Perhaps you want to use an object as a hash key, and
need to make sure that no one modifies it while it's being used.
Perhaps something is corrupting one of your objects, and you'd like
Ruby to raise an exception as soon as the change occurs.
<P></P>
Ruby provides a very simple mechanism to help with this. Any object can be
<em>frozen</em> by invoking <a href="ref_c_object.html#freeze"><code>Object#freeze</code></a>. A frozen object may
not be modified: you can't change its instance variables (directly or
indirectly), you can't associate singleton methods with it, and, if it
is a class or module, you can't add, delete, or modify its
methods. Once frozen, an object stays frozen: there is no
<a href="ref_c_object.html#thaw"><code>Object#thaw</code></a>. You can test to see if an object is frozen using
<a href="ref_c_object.html#frozen_qm"><code>Object#frozen?</code></a>.
<P></P>
What happens when you copy a frozen object? That depends on the method
you use. If you call an object's <code>clone</code> method, the entire
object state (including whether it is frozen) is copied to the new
object. On the other hand, <code>dup</code> typically copies only the
object's contents---the new copy will not inherit the frozen status.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>str1 = "hello"</code></td>
</tr>
<tr>
<td valign="top"><code>str1.freeze</code></td>
<td valign="top"></td>
<td valign="top"><code>"hello"</code></td>
</tr>
<tr>
<td valign="top"><code>str1.frozen?</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>str2 = str1.clone</code></td>
</tr>
<tr>
<td valign="top"><code>str2.frozen?</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>str3 = str1.dup</code></td>
</tr>
<tr>
<td valign="top"><code>str3.frozen?</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
</table>
<P></P>
<P></P>
Although freezing objects may initially seem like a good idea, you
might want to hold off doing it until you come across a real
need. Freezing is one of those ideas that looks essential on paper but
isn't used much in practice.
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="language.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="taint.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>
|