Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Operators and Expressions
What will be the output of this Ruby code?
class Number
  def initialize(n)
    @n = n
  end
  def +(other)
    @n - other
  end
end
num = Number.new(10)
puts num + 3
A7
BError: wrong number of arguments
CError: undefined method `-` for Integer
D13
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the + method

    The + method subtracts other from @n (10 - 3).
  2. Step 2: Calculate the result

    10 - 3 equals 7, so num + 3 returns 7.
  3. Final Answer:

    7 -> Option A
  4. Quick Check:

    Operator method returns 7 = D [OK]
Quick Trick: Operator methods can do anything, not just expected math [OK]
Common Mistakes:
  • Assuming + always adds
  • Confusing subtraction with addition
  • Expecting error due to operator misuse

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes