== operator - How does it work?

B

Bharat Ruparel

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
 
C

ChrisH

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
 
B

Bharat Ruparel

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top