0
0
Rubyprogramming~5 mins

Comparable module usage in Ruby

Choose your learning style9 modes available
Introduction

The Comparable module helps you easily compare objects like numbers or words. It saves time by giving you ready-to-use comparison methods.

When you want to compare custom objects like people by age or books by title.
When you need to sort a list of objects based on some property.
When you want to check if one object is bigger, smaller, or equal to another.
When you want to use operators like <, >, <=, >= on your own classes.
When you want to write cleaner code without repeating comparison logic.
Syntax
Ruby
class YourClass
  include Comparable

  def <=>(other)
    # return -1, 0, or 1 depending on comparison
  end
end

The <=> method is called the spaceship operator. It must return -1, 0, or 1 (or nil if objects are not comparable).

Including Comparable gives you <, <=, ==, >=, > methods automatically.

Examples
This example compares boxes by their volume.
Ruby
class Box
  include Comparable

  attr_reader :volume

  def initialize(volume)
    @volume = volume
  end

  def <=>(other)
    volume <=> other.volume
  end
end
Here, box1 is smaller than box2 because 10 < 20.
Ruby
box1 = Box.new(10)
box2 = Box.new(20)
puts box1 < box2  # true
Sample Program

This program compares two people by their age using Comparable.

Ruby
class Person
  include Comparable

  attr_reader :age

  def initialize(age)
    @age = age
  end

  def <=>(other)
    age <=> other.age
  end
end

alice = Person.new(30)
bob = Person.new(25)

puts alice > bob
puts alice == bob
puts alice < bob
OutputSuccess
Important Notes

Make sure your <=> method returns -1, 0, or 1 for correct behavior, or nil if objects are not comparable.

If you forget to include Comparable, comparison operators won't work automatically.

Comparable works best when your objects have a clear way to be ordered.

Summary

Include Comparable to get comparison operators for your class.

Define the <=> method to tell Ruby how to compare objects.

This makes sorting and comparing objects easy and clean.