Ruby - Array Comparison Customization

Introduction

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.

Demo

class MyArray < Array 
  include Comparable #  w  w w  .ja  v a  2 s.c o  m

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

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

Result

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 
end 

Related Topic