Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Ruby - Advanced Metaprogramming
Consider this code:
class Parent
  def self.inherited(subclass)
    subclass.instance_variable_set(:@count, 0)
  end
end

class Child < Parent; end

p Child.instance_variable_get(:@count)

What is the output and why?
Anil because instance variables are not set this way
B0 because <code>inherited</code> sets @count on subclass
CError because <code>instance_variable_set</code> is invalid
D1 because subclass increments @count automatically
Step-by-Step Solution
Solution:
  1. Step 1: Analyze inherited hook effect

    The hook sets the instance variable @count to 0 on the subclass object.
  2. Step 2: Check output of instance_variable_get

    Since @count was set to 0, printing it returns 0.
  3. Final Answer:

    0 because inherited sets @count on subclass -> Option B
  4. Quick Check:

    Hook sets subclass variable = output 0 [OK]
Quick Trick: Hook can set variables on subclass object [OK]
Common Mistakes:
  • Expecting nil because of misunderstanding variable scope
  • Thinking method call is invalid
  • Assuming automatic increment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes