Bird
0
0

What will be the output of this Ruby code?

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

What will be the output of this Ruby code?

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

box1 = Box.new(10)
box2 = Box.new(20)
puts box1 < box2
Atrue
Bfalse
Cnil
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the <=> method

    The method compares volumes of two Box objects using <=> on integers.
  2. Step 2: Evaluate box1 < box2

    Since 10 < 20, box1 < box2 returns true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Comparison returns true when left is smaller = B [OK]
Quick Trick: Comparable uses <=> to compare object attributes [OK]
Common Mistakes:
  • Expecting output to be false
  • Thinking it returns nil
  • Assuming code raises an error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes