Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Modules and Mixins

What will be the output of this Ruby code?

class Score
  include Comparable
  attr_reader :points
  def initialize(points)
    @points = points
  end
  def <=>(other)
    other.points <=> points
  end
end

s1 = Score.new(50)
s2 = Score.new(75)
puts s1 > s2
Afalse
Btrue
Cnil
DError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the <=> method

    The comparison is reversed: other.points <=> points means higher points come first.
  2. Step 2: Evaluate s1 > s2

    Since s1.points=50 and s2.points=75, reversed comparison means s1 > s2 is true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Reversed <=> flips comparison result = B [OK]
Quick Trick: Reversing <=> flips comparison logic [OK]
Common Mistakes:
  • Ignoring reversed comparison
  • Expecting false because 50 < 75 normally
  • Assuming error due to reversed logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes