Ruby - Array Comparison Customization


The comparison "operator" <=> is defined in the Ruby module named Comparable.

You can include the Comparable module in your own classes.

You can override the <=> method to enable you to define exactly how comparisons will be made between specific object types.

The following code shows how to subclass Array so that comparisons are made based purely on the length of two arrays rather than on the value of each item in the array.


class MyArray < Array 
  include Comparable #   ww  w.  j  ava2 s  . co m

  def <=> ( anotherArray ) 
    self.length <=> anotherArray.length 
myarr1 =[0,1,2,3]) 
myarr2 =[1,2,3,4]) 

                        # Two MyArray objects 
puts myarr1 <=> myarr2  #=> 0


This comparison returns 0, which indicates that the two arrays are equal.

Comparable module included in the MyArray class automatically supplies three comparison methods:

  • <
  • >
  • ==

Each method makes its comparison based on the definition of the <=> method.

Since our <=> makes its evaluation based on the number of items in an array, the < method evaluates to true when the first array is shorter than the second, == evaluates to true when both arrays are of equal length, and > evaluates to true when the second array is longer than the first:

p( myarr1 < myarr2 )    #=> false 
p( myarr1 == myarr2 )   #=> true 

The standard Array class does not include the Comparable module.

So if you try to compare two ordinary arrays using <, ==, or >, Ruby will display an error message telling you that the method is undefined.

It's easy to add these three methods to a subclass of Array:

class Array2 < Array 
  include Comparable 

Related Topic