Bird
0
0

Given this code, what will be printed?

medium📝 Predict Output Q5 of 15
Ruby - Advanced Metaprogramming
Given this code, what will be printed?
class A
  def self.inherited(subclass)
    puts "Inherited by #{subclass}"
  end
end

class B < A; end
class C < B; end
AInherited by B
BInherited by B Inherited by C
CInherited by C
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Identify which class defines inherited

    Only class A defines inherited.
  2. Step 2: Trace subclassing calls

    When B inherits from A, A.inherited(B) runs and prints "Inherited by B". When C inherits from B, B does not define inherited, so no print occurs.
  3. Final Answer:

    Inherited by B -> Option A
  4. Quick Check:

    Hook runs only on direct subclass of A [OK]
Quick Trick: Hook runs only on direct subclasses of defining class [OK]
Common Mistakes:
  • Assuming hook runs on all subclass levels
  • Expecting output for C
  • Confusing inheritance chain behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes