Bird
0
0

Find the error in this Ruby code using the included hook:

medium📝 Debug Q14 of 15
Ruby - Advanced Metaprogramming

Find the error in this Ruby code using the included hook:

module Logger
  def included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def log(msg)
      puts "Log: #{msg}"
    end
  end
end

class App
  include Logger
end

App.log("Start")
AThe include statement should be extend.
BThe ClassMethods module should be included, not extended.
CThe log method should be an instance method, not class method.
DThe included method should be defined as self.included, not instance method.
Step-by-Step Solution
Solution:
  1. Step 1: Check how included hook is defined

    The included hook must be a module method, defined as self.included, not an instance method.
  2. Step 2: Understand the effect of incorrect definition

    Defining included without self means it won't run automatically on include, so base.extend won't happen.
  3. Final Answer:

    The included method should be defined as self.included, not instance method. -> Option D
  4. Quick Check:

    included hook must be self.included [OK]
Quick Trick: Define included as self.included to run on module include [OK]
Common Mistakes:
  • Defining included without self
  • Confusing extend and include in hook
  • Trying to call class method on instance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes