Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Ruby - Advanced Metaprogramming
Consider this code:
module Tracker
  def self.method_added(name)
    puts "Tracked: #{name}"
  end
end

class MyClass
  extend Tracker

  def test; end
end

Why does method_added not print anything when test is defined?
ABecause method_added must be defined as instance method
BBecause extend does not add instance methods
CBecause method_added is defined on the module's singleton class, not MyClass's singleton class
DBecause test is a class method, not instance method
Step-by-Step Solution
Solution:
  1. Step 1: Understand extend behavior

    Using extend Tracker adds Tracker's methods as class methods to MyClass.
  2. Step 2: Check where method_added is defined

    method_added is defined on Tracker's singleton class, not on MyClass's singleton class, so it is not triggered for MyClass instance methods.
  3. Final Answer:

    Because method_added is defined on the module's singleton class, not MyClass's singleton class -> Option C
  4. Quick Check:

    method_added must be on class singleton to catch instance methods [OK]
Quick Trick: method_added triggers only on class singleton, not module singleton [OK]
Common Mistakes:
  • Assuming extend adds instance methods
  • Confusing class and instance methods
  • Expecting method_added to work from module singleton

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes