Ruby - Module Comparable


Comparable module gives other classes comparison operators such as

  • < (less than),
  • <= (less than or equal to),
  • == (equal to),
  • >= (greater than or equal to), and
  • > (greater than), as well as the
  • between? method that returns true if the value is between (inclusively) the two parameters supplied (for example, 4.between?(3,10) == true).

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.

For example:

1 <=> 2 #-1 
1 <=> 1 #0 
2 <=> 1 #1 


class Song 
  include Comparable # from  www  .j av a2 s  .c  om

  attr_accessor :length 
  def <=>(other) 
    @length <=> other.length 

  def initialize(song_name, length) 
    @song_name = song_name 
    @length = length 


a ='Rock around the clock', 143) 
b ='Bohemian Rhapsody', 544) 
c ='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.

Related Topics