Recall & Review
beginner
What is the purpose of the Comparable module in Ruby?
The Comparable module allows objects to be compared using operators like <, <=, ==, >, and >= by defining a single
<=> method.Click to reveal answer
beginner
Which method must be defined in a class to use the Comparable module?You must define the
<=> method (called the spaceship operator) that returns -1, 0, or 1 depending on whether the object is less than, equal to, or greater than another object.Click to reveal answer
intermediate
How does the
<=> method work in the Comparable module?It compares two objects and returns
-1 if the first is less, 0 if equal, and 1 if greater. This single method enables all comparison operators.Click to reveal answer
intermediate
Example: How to include Comparable in a class and define <code><=></code>?class Box
include Comparable
attr_reader :volume
def initialize(volume)
@volume = volume
end
def <=>(other)
volume <=> other.volume
end
end
This lets you compare Box objects by volume.Click to reveal answer
advanced
What happens if you include Comparable but do not define
<=>?Ruby will raise a
NoMethodError when you try to compare objects because Comparable depends on the <=> method to work.Click to reveal answer
What does the
<=> method return when the first object is greater than the second?✗ Incorrect
The
<=> method returns 1 if the first object is greater than the second.Which module do you include to get comparison operators by defining only
<=>?✗ Incorrect
The Comparable module provides comparison operators when you define the
<=> method.If you want to compare objects by their age attribute, what should
<=> return?✗ Incorrect
The
<=> method should return the result of comparing the age attributes using <=>.What error occurs if Comparable is included but
<=> is missing?✗ Incorrect
Ruby raises a NoMethodError because Comparable requires the
<=> method.Which of these operators is NOT provided by including Comparable?
✗ Incorrect
The
=== operator is not provided by Comparable; it is used for case equality and pattern matching.Explain how to use the Comparable module in a Ruby class to enable object comparisons.
Think about what method Comparable needs and what it returns.
You got /4 concepts.
Describe what the spaceship operator (<=>) does and why it is important for Comparable.
It's the heart of how Comparable works.
You got /4 concepts.