Comparable module in Ruby

RubyServer Side ProgrammingProgramming

In Ruby, the class whose objects can be ordered uses the Comparable mixin. Class definitions need to include an operator to compare receivers with each other. The operator will return either -1, 0, or 1.

  • It returns -1 if the receiver is less than another object.

  • If it is greater than another object, then it returns 1.

  • It returns 0 if the receiver is equal to another object.

In the Comparable module, the operator <=> is used to implement the conventional comparison operators (*, <=, ==, >=, and >) and sometimes also between? method as well.

Now that we know a little about the comparable module in Ruby, let's explore a few examples on the same.

Example 1

Consider the code shown below

class TutorialsPoint

# comparable module
include Comparable
attr :key

   def <=>(other_key)
      key.length <=> other_key.key.length
   end

   def initialize(key)
      @key = key
   end
end

# creating objects
a1 = TutorialsPoint.new("T")
a2 = TutorialsPoint.new([3, 6])
a3 = TutorialsPoint.new("tuts")

# comparable operator
puts a1 < a2

# using between? method
puts a2.between?(a1, a3)
puts a3.between?(a1, a2)

Output

true
true
false

In the above example, we used only one operator for comparison; there are 5 more such operators available to us.

Example 2

Consider the code shown below that depicts the use of all these comparison operators.

class TutorialsPoint

# comparable module
include Comparable
attr :key

   def <=>(other_key)
      key.length <=> other_key.key.length
   end

   def initialize(key)
      @key = key
   end
end

# creating objects
a1 = TutorialsPoint.new("T")
a2 = TutorialsPoint.new([3, 6])
a3 = TutorialsPoint.new("tuts")

# comparable operators
puts a1 < a2
puts a1 <= a2
puts a1 == a2
puts a1 >= a2
puts a1 > a2

Output

true
true
false
false
false
raja
Updated on 25-Jan-2022 11:49:27

Advertisements