Bird
0
0

Identify the error in this Ruby code using Comparable:

medium📝 Debug Q6 of 15
Ruby - Modules and Mixins

Identify the error in this Ruby code using Comparable:

class Item
  include Comparable
  attr_reader :weight
  def initialize(weight)
    @weight = weight
  end
  def compare(other)
    weight <=> other.weight
  end
end
ANo error, code is correct
BMissing <code>attr_writer</code> for weight
CShould use <code>extend Comparable</code> instead of <code>include</code>
DMethod name should be <code><=></code>, not <code>compare</code>
Step-by-Step Solution
Solution:
  1. Step 1: Check method name for Comparable

    The required method is <=>, not compare.
  2. Step 2: Confirm other parts

    Other parts like attr_reader and include are correct.
  3. Final Answer:

    Method name should be <=>, not compare -> Option D
  4. Quick Check:

    Define <=> method for Comparable [OK]
Quick Trick: Use exact method name <=> for Comparable [OK]
Common Mistakes:
  • Using wrong method name like compare
  • Confusing include and extend
  • Thinking attr_writer is needed here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes