0
0
Rubyprogramming~3 mins

Why Comparable module usage in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could compare any custom object with just one simple method?

The Scenario

Imagine you have a list of custom objects, like books with different page counts, and you want to sort or compare them manually by writing separate code for each comparison.

The Problem

Writing separate comparison methods for each object type is slow and error-prone. You might forget to update all methods consistently, leading to bugs and duplicated code.

The Solution

The Comparable module lets you define just one method to compare objects, and it automatically provides all other comparison methods like <, >, ==, and more. This saves time and reduces mistakes.

Before vs After
Before
def less_than(other)
  @pages < other.pages
end

def greater_than(other)
  @pages > other.pages
end
After
include Comparable

def <=>(other)
  @pages <=> other.pages
end
What It Enables

It enables easy, consistent comparison and sorting of custom objects with minimal code.

Real Life Example

Sorting a list of books by page count or comparing two products by price becomes simple and reliable.

Key Takeaways

Manual comparisons are repetitive and error-prone.

Comparable module requires defining only one method.

It provides all comparison operators automatically.