Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Metaprogramming Fundamentals
What will be the output of this Ruby code?
Parent = Class.new do
  def speak
    'Parent'
  end
end
Child = Class.new(Parent) do
  def speak
    super + ' Child'
  end
end
puts Child.new.speak
AChild
BParent Child
CParent
DNoMethodError
Step-by-Step Solution
Solution:
  1. Step 1: Understand inheritance with Class.new

    Child inherits from Parent, which has speak returning 'Parent'.
  2. Step 2: Analyze Child's speak method

    Child's speak calls super (Parent's method) and appends ' Child'.
  3. Final Answer:

    Parent Child -> Option B
  4. Quick Check:

    super calls parent method, output concatenated [OK]
Quick Trick: super calls parent method inside Class.new inheritance [OK]
Common Mistakes:
  • Ignoring super call and expecting only 'Child'
  • Confusing method override with error
  • Assuming no inheritance with Class.new

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes