[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

== operator - How does it work?

Bharat Ruparel

2/12/2007 5:09:00 PM

I am running the following code from Programming Ruby book on page 120:

class Song
include Comparable
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def <=>(other)
self.duration <=> other.duration
end
end

song1 = Song.new("My Way", "Sinatra", 225)
song2 = Song.new("Bicylops", "Fleck", 260)

puts song1 == song1

It is printing true for the puts song1 == song2 statement. How are
these two song objects equal?

Thanks in advance for your time.

Bharat

--
Posted via http://www.ruby-....

2 Answers

Chris Hulan

2/12/2007 5:24:00 PM

0

On Feb 12, 12:09 pm, Bharat Ruparel <brupa...@mercury.com> wrote:
> I am running the following code from Programming Ruby book on page 120:
....
> puts song1 == song1
>
> It is printing true for the puts song1 == song2 statement. How are
> these two song objects equal?

Note you have 'song1 == song1' which is of course true.

Based on the implementation of the spaceship op (<=>) and the
inclusion of Comparable,
song2 has a longer duration so is "greater than" song1

HTH
Chris

Bharat Ruparel

2/12/2007 5:56:00 PM

0

Sorry for the bother. I thought I was typing in song1 == song2 and
printing. Whereas I really typed in song1 == song1.
One of those days...
Bharat


--
Posted via http://www.ruby-....