Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Inheritance
What will be the output of this Ruby code?
class Parent
  def add(x, y)
    x + y
  end
end

class Child < Parent
  def add(x, y)
    super(x, y) * 2
  end
end

puts Child.new.add(3, 4)
AError: wrong number of arguments
B7
C14
D10
Step-by-Step Solution
Solution:
  1. Step 1: Trace the parent method call

    The parent method add returns the sum of 3 and 4, which is 7.
  2. Step 2: Apply the child's method logic

    The child calls super(3, 4) which returns 7, then multiplies by 2, resulting in 14.
  3. Final Answer:

    14 -> Option C
  4. Quick Check:

    super returns parent result, child modifies it [OK]
Quick Trick: super returns parent result; child can modify it [OK]
Common Mistakes:
  • Confusing multiplication with addition
  • Expecting error due to arguments
  • Ignoring super call result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes