Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Inheritance
What will be the output of this Ruby code?
class Person
  protected
  def secret
    "protected info"
  end

  public
  def reveal_secret(other)
    other.secret
  end
end

p1 = Person.new
p2 = Person.new
puts p1.reveal_secret(p2)
ASyntaxError
BNoMethodError: protected method `secret' called
Cprotected info
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected method access

    Protected methods can be called by other instances of the same class. Here, p1 calls reveal_secret passing p2, and inside it calls other.secret.
  2. Step 2: Predict output

    Since secret is protected, p1 can call secret on p2. The method returns "protected info", which is printed.
  3. Final Answer:

    protected info -> Option C
  4. Quick Check:

    Protected allows calls between same class instances [OK]
Quick Trick: Protected allows access between same class instances [OK]
Common Mistakes:
  • Thinking protected methods can't be called on other instances
  • Expecting NoMethodError for protected method call
  • Confusing protected with private access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes