Comparable module gives other classes comparison operators such as
The Comparable module uses the <=> comparison operator on the class that includes it.
<=> returns -1 if the supplied parameter is higher than the object's value, 0 if they are equal, or 1 if the object's value is higher than the parameter.
1 <=> 2 #-1 1 <=> 1 #0 2 <=> 1 #1
class Song include Comparable # from w ww. j av a 2 s . c o m attr_accessor :length def <=>(other) @length <=> other.length end def initialize(song_name, length) @song_name = song_name @length = length end end a = Song.new('Rock around the clock', 143) b = Song.new('Bohemian Rhapsody', 544) c = Song.new('Minute Waltz', 60) puts a < b puts b >= c puts c > a puts a.between?(c,b)
You can compare the songs as if you're comparing numbers.
By implementing the <=> method on the Song class, individual song objects can be compared directly.