Bird
0
0

Given this Ruby code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Inheritance
Given this Ruby code, what will be the output?
class Animal
  def sound
    'Some sound'
  end
end

class Dog < Animal
  def sound
    super + ' and Bark'
  end
end

class Cat < Animal
  def sound
    super + ' and Meow'
  end
end

puts Dog.new.sound
puts Cat.new.sound
ASome sound and Bark\nSome sound and Meow
BSome sound\nSome sound
Cand Bark\nand Meow
DError: super called incorrectly
Step-by-Step Solution
Solution:
  1. Step 1: Understand use of super in overridden methods

    Both Dog and Cat override sound and call super to get Animal's sound return value.
  2. Step 2: Combine parent and child method results

    Each child adds its own string to the parent's 'Some sound', resulting in 'Some sound and Bark' and 'Some sound and Meow'.
  3. Final Answer:

    Some sound and Bark\nSome sound and Meow -> Option A
  4. Quick Check:

    super adds parent method result [OK]
Quick Trick: super calls parent method result to extend behavior [OK]
Common Mistakes:
  • Ignoring super and expecting only child string
  • Expecting error from super usage
  • Thinking output is only parent's string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes