What if you could compare any custom object with just one simple method?
Why Comparable module usage in Ruby? - Purpose & Use Cases
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.
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 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.
def less_than(other) @pages < other.pages end def greater_than(other) @pages > other.pages end
include Comparable
def <=>(other)
@pages <=> other.pages
endIt enables easy, consistent comparison and sorting of custom objects with minimal code.
Sorting a list of books by page count or comparing two products by price becomes simple and reliable.
Manual comparisons are repetitive and error-prone.
Comparable module requires defining only one method.
It provides all comparison operators automatically.