Bird
0
0

Identify the issue in this Ruby metaprogramming code:

medium📝 Debug Q6 of 15
Ruby - Metaprogramming Fundamentals
Identify the issue in this Ruby metaprogramming code:
class Sample
  def self.add_method(name, &block)
    define_method(name, &block)
  end

  add_method(:test) do
    puts "Test method called"
  end
end
Aadd_method should be an instance method, not a class method
BThe block passed to add_method is missing a parameter
Cdefine_method cannot be called directly inside a class method without context
DThe method name must be a string, not a symbol
Step-by-Step Solution
Solution:
  1. Step 1: Understand define_method scope

    define_method is a private instance method of Module, used to define instance methods.
  2. Step 2: Analyze the code

    Calling define_method inside a class method (self.add_method) lacks the proper context (self is the class object, not a Module instance).
  3. Step 3: Correct usage

    To define instance methods dynamically, define_method should be called on the class's singleton class or inside class_eval.
  4. Final Answer:

    define_method cannot be called directly inside a class method without context -> Option C
  5. Quick Check:

    define_method needs proper context (Module or class_eval) [OK]
Quick Trick: define_method requires Module context [OK]
Common Mistakes:
  • Calling define_method inside class methods without context
  • Assuming method names must be strings
  • Confusing class and instance methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes