0
0
Rubyprogramming~5 mins

Comparable module usage in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A1
B-1
C0
Dtrue
Which module do you include to get comparison operators by defining only <=>?
AEnumerable
BComparable
CKernel
DMath
If you want to compare objects by their age attribute, what should <=> return?
Aage + other.age
Bage == other.age
Cage <=> other.age
Dage > other.age
What error occurs if Comparable is included but <=> is missing?
ASyntaxError
BArgumentError
CTypeError
DNoMethodError
Which of these operators is NOT provided by including Comparable?
A===
B==
C!=
D<
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.