<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  ref="xref-000001" 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:0x401b299c<nbsp/>@artist=\"Fleck\",<nbsp/>@name=\"Bicylops\",<nbsp/>@duration=260&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:0x401b2a14&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 355.</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 18. 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 18 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 351.
<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 98.
<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 468.</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>537762894</tt></td>
</tr>
<tr>
  <td><tt>Logger.create.id</tt></td>
  <td>&#187;</td>
  <td><tt>537762894</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>537767064</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 31.
<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 251). 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>
