Comparable module usage in Ruby - Time & Space Complexity
We want to understand how the time needed to compare objects grows when using the Comparable module in Ruby.
How does the number of comparisons change as we compare more or bigger objects?
Analyze the time complexity of the following code snippet.
class Box
include Comparable
attr_reader :volume
def initialize(volume)
@volume = volume
end
def <=>(other)
volume <=> other.volume
end
end
box1 = Box.new(10)
box2 = Box.new(20)
puts box1 < box2
This code defines a Box class that can be compared by volume using the Comparable module.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single comparison of two Box objects using the <=> method.
- How many times: Once per comparison call.
Each comparison checks the volume values once, so the time per comparison is constant.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 comparison |
| 100 | 1 comparison |
| 1000 | 1 comparison |
Pattern observation: The time is constant regardless of input size.
Time Complexity: O(1)
This means the time to perform one comparison is constant and does not grow with input size.
[X] Wrong: "Using Comparable makes all comparisons instant regardless of input size."
[OK] Correct: Each comparison still takes time, so if you compare many objects, the total time adds up.
Understanding how comparison operations scale helps you write efficient code when sorting or searching objects, a useful skill in many programming tasks.
"What if the <=> method compared multiple attributes instead of just one? How would the time complexity change?"
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
