Ruby - Module Comparable

Introduction

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 

Demo

class Song 
  include Comparable # ww w .  j  a  v 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)

Result

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