Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Inheritance
What will be the output of this Ruby code?
class Animal
  protected
  def sound
    "growl"
  end

  def call_sound(other)
    other.sound
  end
end

lion = Animal.new
wolf = Animal.new
puts lion.call_sound(wolf)
Agrowl
BNoMethodError
Cnil
DArgumentError
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected method call

    The method sound is protected, so it can be called by instances of the same class on each other.
  2. Step 2: Trace the call

    lion.call_sound(wolf) calls wolf.sound inside the class, which is allowed and returns "growl".
  3. Final Answer:

    growl -> Option A
  4. Quick Check:

    Protected method call between instances = growl [OK]
Quick Trick: Protected methods callable between instances of same class [OK]
Common Mistakes:
  • Expecting NoMethodError due to protected method
  • Thinking protected methods are private and inaccessible
  • Assuming method returns nil instead of string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes