Bird
Raised Fist0
Rubyprogramming~20 mins

Comparable module usage in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Ruby Comparable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of comparing two objects with Comparable
What is the output of this Ruby code using the Comparable module?
Ruby
class Box
  include Comparable
  attr_reader :volume
  def initialize(w, h, d)
    @volume = w * h * d
  end
  def <=>(other)
    volume <=> other.volume
  end
end

box1 = Box.new(2, 3, 4)
box2 = Box.new(3, 2, 4)
puts box1 == box2
puts box1 < box2
puts box1 > box2
A
true
true
false
B
false
true
false
C
false
false
true
D
true
false
false
Attempts:
2 left
💡 Hint
Remember that Comparable uses the <=> method to compare objects.
❓ Predict Output
intermediate
2:00remaining
Sorting objects with Comparable
What will be the output of this Ruby code that sorts objects using Comparable?
Ruby
class Person
  include Comparable
  attr_reader :age
  def initialize(age)
    @age = age
  end
  def <=>(other)
    age <=> other.age
  end
  def to_s
    "Age: #{age}"
  end
end

people = [Person.new(30), Person.new(20), Person.new(25)]
sorted = people.sort
sorted.each { |p| puts p }
A
Age: 30
Age: 25
Age: 20
B
Age: 20
Age: 25
Age: 30
C
Age: 25
Age: 20
Age: 30
D
Age: 20
Age: 30
Age: 25
Attempts:
2 left
💡 Hint
The sort method uses the <=> operator defined in Comparable.
❓ Predict Output
advanced
2:00remaining
Custom comparison with multiple attributes
What is the output of this Ruby code that compares objects by two attributes using Comparable?
Ruby
class Product
  include Comparable
  attr_reader :price, :rating
  def initialize(price, rating)
    @price = price
    @rating = rating
  end
  def <=>(other)
    comp = price <=> other.price
    comp.zero? ? rating <=> other.rating : comp
  end
end

p1 = Product.new(100, 4.5)
p2 = Product.new(100, 4.7)
p3 = Product.new(90, 5.0)

puts p1 > p2
puts p3 < p1
puts p2 == p2
A
false
true
true
B
true
false
true
C
false
false
false
D
true
true
false
Attempts:
2 left
💡 Hint
First compare price, then rating if prices are equal.
❓ Predict Output
advanced
2:00remaining
Effect of missing <=> method in Comparable
What error or output does this Ruby code produce when Comparable is included but <=> is missing?
Ruby
class Item
  include Comparable
  attr_reader :value
  def initialize(value)
    @value = value
  end
end

item1 = Item.new(10)
item2 = Item.new(20)
puts item1 < item2
ANoMethodError: undefined method `<=>` for #<Item:...>
Bfalse
Ctrue
DSyntaxError: unexpected end-of-input
Attempts:
2 left
💡 Hint
Comparable requires <=> method to work.
🧠 Conceptual
expert
2:00remaining
Determining number of items after sorting with Comparable
Given this Ruby code, how many items will be in the sorted array?
Ruby
class Score
  include Comparable
  attr_reader :points
  def initialize(points)
    @points = points
  end
  def <=>(other)
    points <=> other.points
  end
end

scores = [Score.new(10), Score.new(20), Score.new(10), Score.new(30)]
sorted_scores = scores.sort.uniq { |s| s.points }
puts sorted_scores.size
A2
B4
C3
D1
Attempts:
2 left
💡 Hint
uniq with a block removes duplicates based on the block's return value.

Practice

(1/5)
1.

What is the main purpose of including the Comparable module in a Ruby class?

easy
A. To allow the class to inherit from another class
B. To automatically generate getter and setter methods
C. To enable comparison operators like <, <=, ==, >, >= for objects of that class
D. To add string manipulation methods to the class

Solution

  1. Step 1: Understand Comparable module purpose

    The Comparable module provides comparison operators such as <, <=, ==, >, >= for objects.
  2. Step 2: Recognize what including Comparable does

    Including Comparable requires defining the <=> method and then gives the class comparison operators automatically.
  3. Final Answer:

    To enable comparison operators like <, <=, ==, >, >= for objects of that class -> Option C
  4. Quick Check:

    Comparable adds comparison operators = A [OK]
Hint: Comparable adds comparison operators if <=> is defined [OK]
Common Mistakes:
  • Thinking Comparable adds getters/setters
  • Confusing Comparable with inheritance
  • Assuming Comparable adds unrelated methods
2.

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
end
easy
A. @volume <=> other.instance_variable_get(:@volume)
B. self.volume <=> other.volume
C. @volume <=> other.volume
D. @volume <=> other.@volume

Solution

  1. Step 1: Understand instance variable access

    The instance variable @volume is private, so to compare, we must access it properly.
  2. 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.
  3. Final Answer:

    @volume <=> other.instance_variable_get(:@volume) -> Option A
  4. Quick Check:

    Access private var with instance_variable_get = B [OK]
Hint: Use instance_variable_get to access private vars in <=> [OK]
Common Mistakes:
  • Trying to access other.@volume directly (syntax error)
  • Assuming getter methods exist without defining them
  • Using self.volume without a method
3.

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 > p2
medium
A. false
B. true
C. nil
D. Error

Solution

  1. Step 1: Understand the <=> method

    The <=> method compares the ages of two Person objects using age <=> other.age.
  2. Step 2: Compare p1 and p2 using >

    p1.age is 30, p2.age is 25, so 30 > 25 is true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    30 > 25 = true [OK]
Hint: Compare attributes inside <=> for correct operator results [OK]
Common Mistakes:
  • Forgetting to include Comparable
  • Not defining <=> method
  • Confusing attribute names
4.

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
end
medium
A. Method <=> returns a number, should return -1, 0, or 1
B. Syntax error in method definition spacing
C. Missing include Comparable line
D. Cannot call other.weight because no weight method is defined

Solution

  1. Step 1: Check method calls inside <=>

    The code calls other.weight, but no weight method is defined in the class.
  2. Step 2: Fix by adding an attr_reader for weight

    Adding attr_reader :weight allows other.weight to work correctly.
  3. Final Answer:

    Cannot call other.weight because no weight method is defined -> Option D
  4. Quick Check:

    Missing getter method = D [OK]
Hint: Define attr_reader for accessed attributes in <=> [OK]
Common Mistakes:
  • Assuming instance variables are accessible without getters
  • Returning subtraction result instead of using <=> operator
  • Ignoring spacing in method definition (which is valid)
5.

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
end
hard
A. price <=> other.price
B. other.price <=> price
C. price - other.price
D. price > other.price ? 1 : -1

Solution

  1. Step 1: Understand the <=> method contract

    The <=> method should return -1, 0, or 1 depending on comparison.
  2. Step 2: Choose the correct comparison expression

    Using price <=> other.price correctly 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.
  3. Final Answer:

    price <=> other.price -> Option A
  4. Quick Check:

    Use <=> operator for proper comparison = C [OK]
Hint: Use <=> operator directly for clean comparison [OK]
Common Mistakes:
  • Reversing comparison order unintentionally
  • Returning subtraction result instead of <=>
  • Using ternary without zero equality case
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard