Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Operators and Expressions
What will be the output of this Ruby code?
class Box
  attr_reader :value
  def initialize(value)
    @value = value
  end
  def +(other)
    Box.new(@value + other.value)
  end
end

box1 = Box.new(5)
box2 = Box.new(10)
result = box1 + box2
puts result.value
ABox object
B15
C510
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the + method in Box

    The + method adds the @value of two Box objects and returns a new Box with the sum.
  2. Step 2: Calculate the sum and output

    box1 has value 5, box2 has value 10, so result.value is 5 + 10 = 15, which is printed.
  3. Final Answer:

    15 -> Option B
  4. Quick Check:

    5 + 10 = 15 [OK]
Quick Trick: Operator methods can return new objects with combined values [OK]
Common Mistakes:
MISTAKES
  • Expecting string concatenation instead of addition
  • Printing the object instead of its value
  • Confusing method return with side effects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes