Bird
0
0

Why is the included hook defined as a class method (self.included) rather than an instance method in Ruby modules?

hard📝 Conceptual Q10 of 15
Ruby - Advanced Metaprogramming

Why is the included hook defined as a class method (self.included) rather than an instance method in Ruby modules?

ABecause Ruby does not allow instance methods in modules
BBecause it needs to run when the module is included, not when instances are created
CBecause it modifies instance variables of the module
DBecause instance methods cannot be defined inside modules
Step-by-Step Solution
Solution:
  1. Step 1: Understand when included hook runs

    The included hook runs at the moment the module is included into a class or module, not when instances are created.
  2. Step 2: Reason why it must be a class method

    It must be a class method so Ruby can call it on the module itself during inclusion, before any instances exist.
  3. Final Answer:

    Because it needs to run when the module is included, not when instances are created -> Option B
  4. Quick Check:

    Included hook runs on module inclusion, so it's a class method [OK]
Quick Trick: Included hook runs on inclusion, so define as class method [OK]
Common Mistakes:
  • Thinking instance methods can't be in modules
  • Confusing instance creation with module inclusion
  • Assuming included modifies instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes