File: tut_classes.xml

package info (click to toggle)
rubybook 0.2-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 4,252 kB
  • ctags: 1,043
  • sloc: xml: 60,486; makefile: 25
file content (2246 lines) | stat: -rw-r--r-- 67,863 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
<ppdoc>
<copyright>
    Copyright (c) 2001 by Addison Wesley Longman.  This
    material may be distributed only subject to the terms and
    conditions set forth in the Open Publication License, v1.0 or
    later (the latest version is presently available at
    http://www.opencontent.org/openpub/).
</copyright>
<chapter name="Classes, Objects, and Variables">
<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/>
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/>
We'll start off by creating a basic class <classname>Song</classname>,<footnote>As we
  mentioned on page 9, class names start with an
  uppercase letter, while method names start with a lowercase letter.</footnote>
which contains just a single method, <meth>initialize</meth>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
!-    @plays    = 0
  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>def<nbsp/>initialize(name,<nbsp/>artist,<nbsp/>duration)
<nbsp/><nbsp/><nbsp/><nbsp/>@name<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>name
<nbsp/><nbsp/><nbsp/><nbsp/>@artist<nbsp/><nbsp/><nbsp/>=<nbsp/>artist
<nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>duration
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
<meth>initialize</meth> is a special method in Ruby programs. When you
call <ccm><front>Song</front><back>new</back></ccm> to create a new <classname>Song</classname> object, Ruby creates an
uninitialized object and then calls that object's <tt>initialize</tt>
method, passing in any parameters that were passed to
<meth>new</meth>. This gives you a chance to write code that sets up your
object's state.
<p/>
For class <classname>Song</classname>, the <meth>initialize</meth> 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/>
Each object represents its own song, so we need each of our <classname>Song</classname>
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
<var>name</var> is assigned to the instance variable <var>@name</var>,
<var>artist</var> is assigned to <var>@artist</var>, and <var>duration</var> (the
length of the song in seconds) is assigned to <var>@duration</var>.
<p/>
Let's test our spiffy new class.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
!-class Song
!- def inspect
!-  super
!- end
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-  end
!-end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.inspect
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.inspect</tt></td>
  <td>&#187;</td>
  <td><tt>"#&lt;Song:0x4018bfc4<nbsp/><nbsp/>@duration=260,<nbsp/>@artist=\"Fleck\",<nbsp/>@name=\"Bicylops\"&gt;"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Well, it seems to work. By default, the <meth>inspect</meth> 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/>
Our experience tells us that during development we'll be printing out
the contents of a <classname>Song</classname> object many times, and <meth>inspect</meth>'s
default formatting leaves something to be desired. Fortunately, Ruby
has a standard message, <meth>to_s</meth>,
which it
sends to any object it wants to render as a string. Let's try it on
our song.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
!-class Song
!-def to_s
!- super
!- end
!-end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"#&lt;Song:0x4018c1b8&gt;"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
That wasn't too useful---it just reported the object id. So, let's
override <meth>to_s</meth> 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/>
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/>
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/>
Enough detail! Let's get back to adding a <meth>to_s</meth> method to our 
<classname>Song</classname> class.
<p/>
<codefragment>
<fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
  def to_s
    "Song: #{@name}--#{@artist} (#{@duration})"
  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"Song:<nbsp/>#{@name}--#{@artist}<nbsp/>(#{@duration})"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"Song:<nbsp/>Bicylops--Fleck<nbsp/>(260)"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Excellent, we're making progress.  However, we've slipped in something
subtle. We said that Ruby supports <meth>to_s</meth> 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....
<section>Inheritance and Messages</section>
<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 <classname>Song</classname>. 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/>
An approach to this problem is to define a new class, <classname>KaraokeSong</classname>,
which is just like <classname>Song</classname>, but with a lyric track.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end
!-  # Format ourselves as a string by appending
!-  # our lyrics to our parent's #to_s value.
!-  def to_s
!-    super + " [#{@lyrics}]" 
!-  end
end
]]></fullcode>
class<nbsp/>KaraokeSong<nbsp/>&lt;<nbsp/>Song
<nbsp/><nbsp/>def<nbsp/>initialize(name,<nbsp/>artist,<nbsp/>duration,<nbsp/>lyrics)
<nbsp/><nbsp/><nbsp/><nbsp/>super(name,<nbsp/>artist,<nbsp/>duration)
<nbsp/><nbsp/><nbsp/><nbsp/>@lyrics<nbsp/>=<nbsp/>lyrics
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The ``<tt>&lt;<nbsp/>Song</tt>'' on the class definition line tells Ruby that a
<classname>KaraokeSong</classname> is a <em>subclass</em> of <classname>Song</classname>.
(Not surprisingly,
this means that <classname>Song</classname> is a <em>superclass</em> of <classname>KaraokeSong</classname>. People
also talk about parent-child relationships, so <classname>KaraokeSong</classname>'s
parent would be <classname>Song</classname>.) For now, don't worry too much about the
<meth>initialize</meth> method; we'll talk about that <tt>super</tt> call later.
<p/>
Let's create a <classname>KaraokeSong</classname> 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/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
!-class KaraokeSong < Song
!-  def initialize(name, artist, duration, lyrics)
!-    super(name, artist, duration)
!-    @lyrics = lyrics
!-  end
!-  # Format ourselves as a string by appending
!-  # our lyrics to our parent's #to_s value.
!-  def to_s
!-    super + " [#{@lyrics}]" 
!-  end
!-end
!-class KaraokeSong
!-  def to_s
!-    super
!-  end
!-end
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
aSong.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>KaraokeSong.new("My<nbsp/>Way",<nbsp/>"Sinatra",<nbsp/>225,<nbsp/>"And<nbsp/>now,<nbsp/>the...")</tt></td>
</tr>
<tr>
  <td><tt>aSong.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"Song:<nbsp/>My<nbsp/>Way--Sinatra<nbsp/>(225)"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Well, it ran, but why doesn't the <meth>to_s</meth> method show the
lyric?
<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 <tt>aSong.to_s</tt>, it doesn't actually know where to
find the method <meth>to_s</meth>. Instead, it defers the decision until
the program is run. At that time, it looks at the class of <tt>aSong</tt>.
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.<footnote>In fact, you can intercept this error, which allows
  you to fake out methods at runtime. This is described under
  <cim><file>object</file><front>Object</front><back>method_missing</back><mref>method_missing</mref></cim> on page 360.</footnote>
<p/>
So, back to our example. We sent the message <meth>to_s</meth> to
<tt>aSong</tt>, an object of class <classname>KaraokeSong</classname>.
Ruby looks in
<classname>KaraokeSong</classname> for a method called <meth>to_s</meth>, but doesn't find
it. The interpreter then looks in <classname>KaraokeSong</classname>'s parent, class
<classname>Song</classname>, and there it finds the <meth>to_s</meth> method that we defined
on page 20. That's why it prints out the song details but
not the lyrics---class <classname>Song</classname> doesn't know anything about lyrics.
<p/>
Let's fix this by implementing <cim><front>KaraokeSong</front><back>to_s</back></cim>. There are a
number of ways to do this. Let's start with a bad way. We'll copy
the <meth>to_s</meth> method from <classname>Song</classname> and add on the lyric.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
!-class KaraokeSong < Song
!-  def initialize(name, artist, duration, lyrics)
!-    super(name, artist, duration)
!-    @lyrics = lyrics
!-  end
!-  # Format ourselves as a string by appending
!-  # our lyrics to our parent's #to_s value.
!-  def to_s
!-    super + " [#{@lyrics}]" 
!-  end
!-end
class KaraokeSong
  # ...
  def to_s
    "KS: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}]" 
  end
end
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
aSong.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>KaraokeSong</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>#<nbsp/>...</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>"KS:<nbsp/>#{@name}--#{@artist}<nbsp/>(#{@duration})<nbsp/>[#{@lyrics}]"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>KaraokeSong.new("My<nbsp/>Way",<nbsp/>"Sinatra",<nbsp/>225,<nbsp/>"And<nbsp/>now,<nbsp/>the...")</tt></td>
</tr>
<tr>
  <td><tt>aSong.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"KS:<nbsp/>My<nbsp/>Way--Sinatra<nbsp/>(225)<nbsp/>[And<nbsp/>now,<nbsp/>the...]"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
We're correctly displaying the value of the <var>@lyrics</var> instance
variable. To do this, the subclass directly accesses the instance
variables of its ancestors. So why is this a bad way to implement
<meth>to_s</meth>?
<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 <classname>Song</classname> to store the duration in milliseconds. Suddenly,
<classname>KaraokeSong</classname> 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/>
We get around this problem by having each class handle its own
internal state. When <cim><front>KaraokeSong</front><back>to_s</back></cim> is called, we'll have it call
its parent's <meth>to_s</meth> 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 ``<kw>super</kw>''. When you invoke
<kw>super</kw> 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
<meth>to_s</meth>.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
class KaraokeSong < Song
!-  def initialize(name, artist, duration, lyrics)
!-    super(name, artist, duration)
!-    @lyrics = lyrics
!-  end
  # Format ourselves as a string by appending
  # our lyrics to our parent's #to_s value.
  def to_s
    super + " [#{@lyrics}]" 
  end
end
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
aSong.to_s
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>KaraokeSong<nbsp/>&lt;<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>#<nbsp/>Format<nbsp/>ourselves<nbsp/>as<nbsp/>a<nbsp/>string<nbsp/>by<nbsp/>appending</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>#<nbsp/>our<nbsp/>lyrics<nbsp/>to<nbsp/>our<nbsp/>parent's<nbsp/>#to_s<nbsp/>value.</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>to_s</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>super<nbsp/>+<nbsp/>"<nbsp/>[#{@lyrics}]"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>KaraokeSong.new("My<nbsp/>Way",<nbsp/>"Sinatra",<nbsp/>225,<nbsp/>"And<nbsp/>now,<nbsp/>the...")</tt></td>
</tr>
<tr>
  <td><tt>aSong.to_s</tt></td>
  <td>&#187;</td>
  <td><tt>"Song:<nbsp/>My<nbsp/>Way--Sinatra<nbsp/>(225)<nbsp/>[And<nbsp/>now,<nbsp/>the...]"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
We explicitly told Ruby that <tt>KaraokeSong</tt> was a subclass of
<classname>Song</classname>, but we didn't specify a parent class for <classname>Song</classname> itself. If
you don't specify a parent when defining a class, Ruby supplies
class <classname>Object</classname> as a default. This means that all objects have
<classname>Object</classname> as an ancestor, and that <classname>Object</classname>'s instance methods are
available to every object in Ruby. Back on page 20 we said
that <meth>to_s</meth> is available to all objects. Now we know why;
<meth>to_s</meth> is one of more than 35 instance methods in
class <classname>Object</classname>. The complete list begins on page 356.
<subsection>Inheritance and Mixins</subsection>
<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/>
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/>
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/>
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 <classname>Song</classname>.
<section>Objects and Attributes</section>
<p/>
The <classname>Song</classname> 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/>
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/>
For our <classname>Song</classname> 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/>
<codefragment>
<fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
  def name
    @name
  end
  def artist
    @artist
  end
  def duration
    @duration
  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.artist
aSong.name
aSong.duration
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>name</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@name</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>artist</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@artist</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>duration</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@duration</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.artist</tt></td>
  <td>&#187;</td>
  <td><tt>"Fleck"</tt></td>
</tr>
<tr>
  <td><tt>aSong.name</tt></td>
  <td>&#187;</td>
  <td><tt>"Bicylops"</tt></td>
</tr>
<tr>
  <td><tt>aSong.duration</tt></td>
  <td>&#187;</td>
  <td><tt>260</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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: <meth>attr_reader</meth> creates these
accessor methods for you.
<p/>
<codefragment>
<fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.artist
aSong.name
aSong.duration
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>attr_reader<nbsp/>:name,<nbsp/>:artist,<nbsp/>:duration</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.artist</tt></td>
  <td>&#187;</td>
  <td><tt>"Fleck"</tt></td>
</tr>
<tr>
  <td><tt>aSong.name</tt></td>
  <td>&#187;</td>
  <td><tt>"Bicylops"</tt></td>
</tr>
<tr>
  <td><tt>aSong.duration</tt></td>
  <td>&#187;</td>
  <td><tt>260</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
This example has introduced something new. The construct <tt>:artist</tt>
is an expression that returns a <classname>Symbol</classname> object corresponding to
<tt>artist</tt>. You can think of <tt>:artist</tt> as meaning the <em>name</em>
of the variable <tt>artist</tt>, while plain <tt>artist</tt> is the
<em>value</em> of the variable. In this example, we named the accessor
methods <var>name</var>, <var>artist</var>, and <var>duration</var>.  The
corresponding instance variables, <var>@name</var>, <var>@artist</var>, and
<var>@duration</var>, will be created automatically.  These accessor methods
are identical to the ones we wrote by hand earlier.
<subsection>Writable Attributes</subsection>
<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 <classname>Song</classname> object.
<p/>
In languages such as C++ and Java, you'd do this with <em>setter
  functions</em>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class JavaSong {                     // Java code
    private Duration myDuration;
    public void setDuration(Duration newDuration) {
      myDuration = newDuration;
    }
  }
  s = new Song(....)
  s.setDuration(length)
]]></fullcode>
class<nbsp/>JavaSong<nbsp/>{<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>//<nbsp/>Java<nbsp/>code
<nbsp/><nbsp/>private<nbsp/>Duration<nbsp/>myDuration;
<nbsp/><nbsp/>public<nbsp/>void<nbsp/>setDuration(Duration<nbsp/>newDuration)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>myDuration<nbsp/>=<nbsp/>newDuration;
<nbsp/><nbsp/>}
}
s<nbsp/>=<nbsp/>new<nbsp/>Song(....)
s.setDuration(length)
</alltt>
</codefragment>
<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
<tt>aSong.name</tt>. 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/>
<codefragment>
<fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
  def duration=(newDuration)
    @duration = newDuration
  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration
aSong.duration = 257   # set attribute with updated value
aSong.duration
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>duration=(newDuration)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>newDuration</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.duration</tt></td>
  <td>&#187;</td>
  <td><tt>260</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong.duration<nbsp/>=<nbsp/>257<nbsp/><nbsp/><nbsp/>#<nbsp/>set<nbsp/>attribute<nbsp/>with<nbsp/>updated<nbsp/>value</tt></td>
</tr>
<tr>
  <td><tt>aSong.duration</tt></td>
  <td>&#187;</td>
  <td><tt>257</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
The assignment ``<tt>aSong.duration<nbsp/>=<nbsp/>257</tt>'' invokes the method
<meth>duration=</meth> in the <tt>aSong</tt> object, passing it <tt>257</tt> 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/>
Again, Ruby provides a shortcut for creating these simple attribute
setting methods.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration = 257
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>attr_writer<nbsp/>:duration
end
aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)
aSong.duration<nbsp/>=<nbsp/>257
</alltt>
</codefragment>
<subsection>Virtual Attributes</subsection>
<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/>
<codefragment>
<fullcode><![CDATA[class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
  def durationInMinutes
    @duration/60.0   # force floating point
  end
  def durationInMinutes=(value)
    @duration = (value*60).to_i
  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.durationInMinutes
aSong.durationInMinutes = 4.2
aSong.duration
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>Song</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>durationInMinutes</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@duration/60.0<nbsp/><nbsp/><nbsp/>#<nbsp/>force<nbsp/>floating<nbsp/>point</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>durationInMinutes=(value)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>(value*60).to_i</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>aSong.durationInMinutes</tt></td>
  <td>&#187;</td>
  <td><tt>4.333333333</tt></td>
</tr>
<tr>
<td colspan="3"><tt>aSong.durationInMinutes<nbsp/>=<nbsp/>4.2</tt></td>
</tr>
<tr>
  <td><tt>aSong.duration</tt></td>
  <td>&#187;</td>
  <td><tt>252</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Here we've used attribute methods to create a virtual instance
variable. To the outside world, <tt>durationInMinutes</tt> seems to be an
attribute like any other. Internally, though, there is no
corresponding instance variable.
<p/>
This is more than a curiosity. In his landmark book
<em>Object-Oriented Software Construction</em><nbsp/>,
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.
<section>Class Variables and Class Methods</section>
<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.
<subsection>Class Variables</subsection>
<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 ``<tt>@@count</tt>''.
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/>
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 <classname>Song</classname> 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 <classname>Song</classname> 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/>
<codefragment>
<alltt><fullcode><![CDATA[class Song
!-  include Comparable
  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
  def play
    @plays += 1
    @@plays += 1
    "This  song: #@plays plays. Total #@@plays plays."
  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
end
]]></fullcode>
class<nbsp/>Song
<nbsp/><nbsp/>@@plays<nbsp/>=<nbsp/>0
<nbsp/><nbsp/>def<nbsp/>initialize(name,<nbsp/>artist,<nbsp/>duration)
<nbsp/><nbsp/><nbsp/><nbsp/>@name<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>name
<nbsp/><nbsp/><nbsp/><nbsp/>@artist<nbsp/><nbsp/><nbsp/>=<nbsp/>artist
<nbsp/><nbsp/><nbsp/><nbsp/>@duration<nbsp/>=<nbsp/>duration
<nbsp/><nbsp/><nbsp/><nbsp/>@plays<nbsp/><nbsp/><nbsp/><nbsp/>=<nbsp/>0
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>play
<nbsp/><nbsp/><nbsp/><nbsp/>@plays<nbsp/>+=<nbsp/>1
<nbsp/><nbsp/><nbsp/><nbsp/>@@plays<nbsp/>+=<nbsp/>1
<nbsp/><nbsp/><nbsp/><nbsp/>"This<nbsp/><nbsp/>song:<nbsp/>#@plays<nbsp/>plays.<nbsp/>Total<nbsp/>#@@plays<nbsp/>plays."
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
For debugging purposes, we've arranged for <cim><front>Song</front><back>play</back></cim> 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/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
s1 = Song.new("Song1", "Artist1", 234)  # test songs..
s2 = Song.new("Song2", "Artist2", 345)
s1.play
s2.play
s1.play
s1.play
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>s1<nbsp/>=<nbsp/>Song.new("Song1",<nbsp/>"Artist1",<nbsp/>234)<nbsp/><nbsp/>#<nbsp/>test<nbsp/>songs..</tt></td>
</tr>
<tr>
<td colspan="3"><tt>s2<nbsp/>=<nbsp/>Song.new("Song2",<nbsp/>"Artist2",<nbsp/>345)</tt></td>
</tr>
<tr>
  <td><tt>s1.play</tt></td>
  <td>&#187;</td>
  <td><tt>"This<nbsp/><nbsp/>song:<nbsp/>1<nbsp/>plays.<nbsp/>Total<nbsp/>1<nbsp/>plays."</tt></td>
</tr>
<tr>
  <td><tt>s2.play</tt></td>
  <td>&#187;</td>
  <td><tt>"This<nbsp/><nbsp/>song:<nbsp/>1<nbsp/>plays.<nbsp/>Total<nbsp/>2<nbsp/>plays."</tt></td>
</tr>
<tr>
  <td><tt>s1.play</tt></td>
  <td>&#187;</td>
  <td><tt>"This<nbsp/><nbsp/>song:<nbsp/>2<nbsp/>plays.<nbsp/>Total<nbsp/>3<nbsp/>plays."</tt></td>
</tr>
<tr>
  <td><tt>s1.play</tt></td>
  <td>&#187;</td>
  <td><tt>"This<nbsp/><nbsp/>song:<nbsp/>3<nbsp/>plays.<nbsp/>Total<nbsp/>4<nbsp/>plays."</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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.
<subsection>Class Methods</subsection>
<p/>
Sometimes a class needs to provide methods that work without being tied 
to any particular object.
<p/>
We've already come across one such method.
The <meth>new</meth> method creates a new <classname>Song</classname> object but is not
itself associated with a particular song. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  aSong = Song.new(....)
]]></fullcode>
aSong<nbsp/>=<nbsp/>Song.new(....)
</alltt>
</codefragment>
<p/>
You'll find class methods sprinkled throughout the Ruby libraries. For
example, objects of class <classname>File</classname> represent open files
in the underlying file system. However, class <classname>File</classname> also provides
several class methods for manipulating files that aren't open and
therefore don't have a <classname>File</classname> object. If you want to delete a file,
you call the class method <ccm><file>file</file><front>File</front><back>delete</back><mref>delete</mref></ccm>, passing in the name.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  File.delete("doomedFile")
]]></fullcode>
File.delete("doomedFile")
</alltt>
</codefragment>
<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/>
<codefragment>
<alltt><fullcode><![CDATA[  class Example
  
    def instMeth              # instance method
    end

    def Example.classMeth     # class method
    end

  end
]]></fullcode>
class<nbsp/>Example
<p/>
<nbsp/><nbsp/>def<nbsp/>instMeth<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>instance<nbsp/>method
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>Example.classMeth<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>class<nbsp/>method
<nbsp/><nbsp/>end
<p/>
end
</alltt>
</codefragment>
<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 <classname>SongList</classname> 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/>
<codefragment>
<fullcode><![CDATA[!-class Song
!-  include Comparable
!-  @@plays = 0
!-  attr_reader :name, :artist, :duration
!-  attr_writer :duration
!-  def initialize(name, artist, duration)
!-    @name     = name
!-    @artist   = artist
!-    @duration = duration
!-    @plays    = 0
!-  end
!-  def to_s
!-    "Song: #{@name}--#{@artist} (#{@duration})"
!-  end
!-  def name
!-    @name
!-  end
!-  def artist
!-    @artist
!-  end
!-  def duration
!-    @duration
!-  end
!-  def duration=(newDuration)
!-    @duration = newDuration
!-  end
!-  def durationInMinutes
!-    @duration/60.0   # force floating point
!-  end
!-  def durationInMinutes=(value)
!-    @duration = (value*60).to_i
!-  end
!-  def play
!-    @plays += 1
!-    @@plays += 1
!-    "This  song: #@plays plays. Total #@@plays plays."
!-  end
!-  def record
!-    "Recording..."
!-  end
!-  def inspect
!-    self.to_s
!-  end
!-  def <=>(other)
!-    self.duration <=> other.duration
!-  end
!-end
  class SongList
    MaxTime = 5*60           #  5 minutes
    
    def SongList.isTooLong(aSong)
      return aSong.duration > MaxTime
    end
  end
  song1 = Song.new("Bicylops", "Fleck", 260)
  SongList.isTooLong(song1)
  song2 = Song.new("The Calling", "Santana", 468)
  SongList.isTooLong(song2)
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>class<nbsp/>SongList</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>MaxTime<nbsp/>=<nbsp/>5*60<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/><nbsp/>5<nbsp/>minutes</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>def<nbsp/>SongList.isTooLong(aSong)</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>aSong.duration<nbsp/>&gt;<nbsp/>MaxTime</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>end</tt></td>
</tr>
<tr>
<td colspan="3"><tt>song1<nbsp/>=<nbsp/>Song.new("Bicylops",<nbsp/>"Fleck",<nbsp/>260)</tt></td>
</tr>
<tr>
  <td><tt>SongList.isTooLong(song1)</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
<tr>
<td colspan="3"><tt>song2<nbsp/>=<nbsp/>Song.new("The<nbsp/>Calling",<nbsp/>"Santana",<nbsp/>468)</tt></td>
</tr>
<tr>
  <td><tt>SongList.isTooLong(song2)</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Singletons and Other Constructors</subsection>
<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/>
Enter the Singleton pattern, documented in <em>Design
  Patterns</em><nbsp/>.
We'll arrange things so that the
only way to create a logging object is to call <ccm><front>Logger</front><back>create</back></ccm>,
and we'll ensure that only one logging object is ever created.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Logger
  private_class_method :new
  @@logger = nil
  def Logger.create
    @@logger = new unless @@logger
    @@logger
  end
end
]]></fullcode>
class<nbsp/>Logger
<nbsp/><nbsp/>private_class_method<nbsp/>:new
<nbsp/><nbsp/>@@logger<nbsp/>=<nbsp/>nil
<nbsp/><nbsp/>def<nbsp/>Logger.create
<nbsp/><nbsp/><nbsp/><nbsp/>@@logger<nbsp/>=<nbsp/>new<nbsp/>unless<nbsp/>@@logger
<nbsp/><nbsp/><nbsp/><nbsp/>@@logger
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
By making <classname>Logger</classname>'s method <meth>new</meth> private, we prevent anyone from
creating a logging object using the conventional constructor. Instead, we provide a class method,
<ccm><front>Logger</front><back>create</back></ccm>. This uses the class variable <var>@@logger</var> to
keep a reference to a single instance of the logger, returning that
instance every time it is called.<footnote>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 <modulename>Singleton</modulename> mixin supplied with Ruby, which is
  documented on page 472.</footnote> We can check this by looking
at the object identifiers the method returns.
<p/>
<codefragment>
<fullcode><![CDATA[!-class Logger
!-  private_class_method :new
!-  @@logger = nil
!-  def Logger.create
!-    @@logger = new unless @@logger
!-    @@logger
!-  end
!-end
Logger.create.id
Logger.create.id
]]></fullcode><rubycode>
<tr>
  <td><tt>Logger.create.id</tt></td>
  <td>&#187;</td>
  <td><tt>537684700</tt></td>
</tr>
<tr>
  <td><tt>Logger.create.id</tt></td>
  <td>&#187;</td>
  <td><tt>537684700</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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
<classname>Shape</classname> that represents a regular polygon. Instances of <classname>Shape</classname>
are created by giving the constructor the required number of sides and 
the total perimeter.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Shape
  def initialize(numSides, perimeter)
    # ...
  end
!-  def Shape.triangle(sideLength)
!-    Shape.new(3, sideLength*3)
!-  end
!-  def Shape.square(sideLength)
!-    Shape.new(4, sideLength*4)
!-  end
end
]]></fullcode>
class<nbsp/>Shape
<nbsp/><nbsp/>def<nbsp/>initialize(numSides,<nbsp/>perimeter)
<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>...
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<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 <classname>Shape</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[class Shape
!-  def initialize(numSides, perimeter)
!-    # ...
!-  end
  def Shape.triangle(sideLength)
    Shape.new(3, sideLength*3)
  end
  def Shape.square(sideLength)
    Shape.new(4, sideLength*4)
  end
end
]]></fullcode>
class<nbsp/>Shape
<nbsp/><nbsp/>def<nbsp/>Shape.triangle(sideLength)
<nbsp/><nbsp/><nbsp/><nbsp/>Shape.new(3,<nbsp/>sideLength*3)
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>Shape.square(sideLength)
<nbsp/><nbsp/><nbsp/><nbsp/>Shape.new(4,<nbsp/>sideLength*4)
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<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.
<section>Access Control</section>
<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/>
<ul>
<li> <b>Public methods</b> can be called by anyone---there is no
  access control. Methods are public by default (except for
  <meth>initialize</meth>, 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/>
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/>
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.
<subsection>Specifying Access Control</subsection>
<p/>
You specify access levels to methods within class or module
definitions using one or more of the three functions <kw>public</kw>,
<kw>protected</kw>, and <kw>private</kw>. Each function can be used in two
different ways.
<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 <kw>public</kw> to achieve the same effect.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class MyClass

        def method1    # default is 'public'
          #...
        end

    protected          # subsequent methods will be 'protected'

        def method2    # will be 'protected'
          #...
        end

    private            # subsequent methods will be 'private'

        def method3    # will be 'private'
          #...
        end

    public             # subsequent methods will be 'public'

        def method4    # and this will be 'public'
          #...
        end
  end
]]></fullcode>
class<nbsp/>MyClass
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>method1<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>default<nbsp/>is<nbsp/>'public'
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#...
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>protected<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>subsequent<nbsp/>methods<nbsp/>will<nbsp/>be<nbsp/>'protected'
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>method2<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>will<nbsp/>be<nbsp/>'protected'
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#...
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>private<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>subsequent<nbsp/>methods<nbsp/>will<nbsp/>be<nbsp/>'private'
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>method3<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>will<nbsp/>be<nbsp/>'private'
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#...
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>public<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>subsequent<nbsp/>methods<nbsp/>will<nbsp/>be<nbsp/>'public'
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>method4<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>and<nbsp/>this<nbsp/>will<nbsp/>be<nbsp/>'public'
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#...
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Alternatively, you can set access levels of named methods by listing
them as arguments to the access control functions.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class MyClass

    def method1
    end

    # ... and so on
!-      def method2() end
!-      def method3() end
!-      def method4() end

    public    :method1, :method4
    protected :method2
    private   :method3
  end
]]></fullcode>
class<nbsp/>MyClass
<p/>
<nbsp/><nbsp/>def<nbsp/>method1
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>#<nbsp/>...<nbsp/>and<nbsp/>so<nbsp/>on
<p/>
<nbsp/><nbsp/>public<nbsp/><nbsp/><nbsp/><nbsp/>:method1,<nbsp/>:method4
<nbsp/><nbsp/>protected<nbsp/>:method2
<nbsp/><nbsp/>private<nbsp/><nbsp/><nbsp/>:method3
end
</alltt>
</codefragment>
<p/>
A class's <meth>initialize</meth> method is automatically declared 
to be private.
<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/>
<codefragment>
<alltt><fullcode><![CDATA[  class Accounts

    private

      def debit(account, amount)
        account.balance -= amount
      end
      def credit(account, amount)
        account.balance += amount
      end

    public

      #...
      def transferToSavings(amount)
        debit(@checking, amount)
        credit(@savings, amount)
      end
      #...
  end
]]></fullcode>
class<nbsp/>Accounts
<p/>
<nbsp/><nbsp/>private
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>debit(account,<nbsp/>amount)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>account.balance<nbsp/>-=<nbsp/>amount
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>credit(account,<nbsp/>amount)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>account.balance<nbsp/>+=<nbsp/>amount
<nbsp/><nbsp/><nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>public
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/>#...
<nbsp/><nbsp/><nbsp/><nbsp/>def<nbsp/>transferToSavings(amount)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>debit(@checking,<nbsp/>amount)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>credit(@savings,<nbsp/>amount)
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>#...
end
</alltt>
</codefragment>
<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 <classname>Account</classname> 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/>
<codefragment>
<alltt><fullcode><![CDATA[  class Account
    attr_reader :balance       # accessor method 'balance'

    protected :balance         # and make it protected

    def greaterBalanceThan(other)
      return @balance > other.balance
    end
  end
]]></fullcode>
class<nbsp/>Account
<nbsp/><nbsp/>attr_reader<nbsp/>:balance<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>accessor<nbsp/>method<nbsp/>'balance'
<p/>
<nbsp/><nbsp/>protected<nbsp/>:balance<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>and<nbsp/>make<nbsp/>it<nbsp/>protected
<p/>
<nbsp/><nbsp/>def<nbsp/>greaterBalanceThan(other)
<nbsp/><nbsp/><nbsp/><nbsp/>return<nbsp/>@balance<nbsp/>&gt;<nbsp/>other.balance
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Because the attribute <meth>balance</meth> is protected, it's available
only within <classname>Account</classname> objects.
<section>Variables</section>
<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/>
<figure type="figure">Figure not available...</figure>
<p/>
Let's confirm this with some code.
<p/>
<codefragment>
<fullcode><![CDATA[  person = "Tim"
  person.id
  person.type
  person
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>person<nbsp/>=<nbsp/>"Tim"</tt></td>
</tr>
<tr>
  <td><tt>person.id</tt></td>
  <td>&#187;</td>
  <td><tt>537684980</tt></td>
</tr>
<tr>
  <td><tt>person.type</tt></td>
  <td>&#187;</td>
  <td><tt>String</tt></td>
</tr>
<tr>
  <td><tt>person</tt></td>
  <td>&#187;</td>
  <td><tt>"Tim"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
On the first line, Ruby creates a new <tt>String</tt> object with the
value ``Tim.'' A reference to this object is placed in the local
variable <var>person</var>.
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/>
So, is a variable an object?
<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/>
Let's make the example slightly more complicated.
<p/>
<codefragment>
<fullcode><![CDATA[  person1 = "Tim"
  person2 = person1

  person1[0] = 'J'
  
  person1
  person2
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>person1<nbsp/>=<nbsp/>"Tim"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>person2<nbsp/>=<nbsp/>person1</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>person1[0]<nbsp/>=<nbsp/>'J'</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>person1</tt></td>
  <td>&#187;</td>
  <td><tt>"Jim"</tt></td>
</tr>
<tr>
  <td><tt>person2</tt></td>
  <td>&#187;</td>
  <td><tt>"Jim"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
What happened here? We changed the first character of
<var>person1</var>, but both <var>person1</var> and <var>person2</var>
changed from ``Tim'' to ``Jim.''
<p/>
It all comes back to the fact that variables hold references to
objects, not the objects themselves. The assignment of <var>person1</var>
to <var>person2</var> doesn't create any new objects; it simply copies
<var>person1</var>'s object reference to <var>person2</var>, so that both
<var>person1</var> and <var>person2</var> refer to the same object.  We show
this in Figure 3.1 on page 33.
<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 <meth>dup</meth>
method of <classname>String</classname>, which creates a new <classname>String</classname> object with identical
contents.
<p/>
<codefragment>
<fullcode><![CDATA[  person1 = "Tim"
  person2 = person1.dup
  person1[0] = "J"
  person1
  person2
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>person1<nbsp/>=<nbsp/>"Tim"</tt></td>
</tr>
<tr>
<td colspan="3"><tt>person2<nbsp/>=<nbsp/>person1.dup</tt></td>
</tr>
<tr>
<td colspan="3"><tt>person1[0]<nbsp/>=<nbsp/>"J"</tt></td>
</tr>
<tr>
  <td><tt>person1</tt></td>
  <td>&#187;</td>
  <td><tt>"Jim"</tt></td>
</tr>
<tr>
  <td><tt>person2</tt></td>
  <td>&#187;</td>
  <td><tt>"Tim"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<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 <exception>TypeError</exception> exception.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  person1 = "Tim"
  person2 = person1
  person1.freeze       # prevent modifications to the object
  person2[0] = "J"
]]></fullcode>
person1<nbsp/>=<nbsp/>"Tim"
person2<nbsp/>=<nbsp/>person1
person1.freeze<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>prevent<nbsp/>modifications<nbsp/>to<nbsp/>the<nbsp/>object
person2[0]<nbsp/>=<nbsp/>"J"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
prog.rb:4:in<nbsp/>`=':<nbsp/>can't<nbsp/>modify<nbsp/>frozen<nbsp/>string<nbsp/>(TypeError)
	from<nbsp/>prog.rb:4
</alltt>
</codefragment>
</chapter>
</ppdoc>