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.
Practice
What is the main purpose of including the Comparable module in a Ruby class?
Solution
Step 1: Understand Comparable module purpose
The Comparable module provides comparison operators such as <, <=, ==, >, >= for objects.Step 2: Recognize what including Comparable does
Including Comparable requires defining the<=>method and then gives the class comparison operators automatically.Final Answer:
To enable comparison operators like <, <=, ==, >, >= for objects of that class -> Option CQuick Check:
Comparable adds comparison operators = A [OK]
- Thinking Comparable adds getters/setters
- Confusing Comparable with inheritance
- Assuming Comparable adds unrelated methods
Which of the following is the correct way to define the comparison method <=> inside a Ruby class to use with Comparable?
class Box
include Comparable
def initialize(volume)
@volume = volume
end
def <=>(other)
?
end
endSolution
Step 1: Understand instance variable access
The instance variable @volume is private, so to compare, we must access it properly.Step 2: Check each option for syntax and correctness
self.volume <=> other.volume uses self.volume but no getter method is defined, so it fails. @volume <=> other.volume tries other.volume but no method exists. @volume <=> other.instance_variable_get(:@volume) uses other.instance_variable_get(:@volume), which accesses the variable correctly. @volume <=> other.@volume uses invalid syntax other.@volume.Final Answer:
@volume <=> other.instance_variable_get(:@volume) -> Option AQuick Check:
Access private var with instance_variable_get = B [OK]
- Trying to access other.@volume directly (syntax error)
- Assuming getter methods exist without defining them
- Using self.volume without a method
What will be the output of the following Ruby code?
class Person
include Comparable
attr_reader :age
def initialize(age)
@age = age
end
def <=>(other)
age <=> other.age
end
end
p1 = Person.new(30)
p2 = Person.new(25)
puts p1 > p2Solution
Step 1: Understand the
The<=>method<=>method compares the ages of two Person objects usingage <=> other.age.Step 2: Compare p1 and p2 using >
p1.age is 30, p2.age is 25, so 30 > 25 is true.Final Answer:
true -> Option BQuick Check:
30 > 25 = true [OK]
- Forgetting to include Comparable
- Not defining <=> method
- Confusing attribute names
Identify the error in this Ruby class using Comparable and how to fix it:
class Item
include Comparable
def initialize(weight)
@weight = weight
end
def <=>(other)
@weight - other.weight
end
endSolution
Step 1: Check method calls inside
The code calls<=>other.weight, but noweightmethod is defined in the class.Step 2: Fix by adding an attr_reader for weight
Addingattr_reader :weightallowsother.weightto work correctly.Final Answer:
Cannot call other.weight because no weight method is defined -> Option DQuick Check:
Missing getter method = D [OK]
- Assuming instance variables are accessible without getters
- Returning subtraction result instead of using <=> operator
- Ignoring spacing in method definition (which is valid)
You want to sort an array of Product objects by their price using Comparable. Which of the following is the best way to implement the <=> method?
class Product
include Comparable
attr_reader :price
def initialize(price)
@price = price
end
def <=>(other)
?
end
endSolution
Step 1: Understand the
The<=>method contract<=>method should return -1, 0, or 1 depending on comparison.Step 2: Choose the correct comparison expression
Usingprice <=> other.pricecorrectly returns -1, 0, or 1. other.price <=> price reverses order, sorting descending. price - other.price returns a number but not guaranteed -1,0,1. price > other.price ? 1 : -1 returns only 1 or -1, missing 0 case.Final Answer:
price <=> other.price -> Option AQuick Check:
Use <=> operator for proper comparison = C [OK]
- Reversing comparison order unintentionally
- Returning subtraction result instead of <=>
- Using ternary without zero equality case
Ready to prove it?
Pass the test and this pattern moves unknown
