Bird
0
0

Identify the bug in this Ruby code using metaprogramming:

medium📝 Debug Q7 of 15
Ruby - Metaprogramming Fundamentals
Identify the bug in this Ruby code using metaprogramming:
class Example
  def self.create_methods(*names)
    names.each do |name|
      define_method(name) { "Hello #{name}" }
    end
  end

  create_methods(:foo, :bar)
end

ex = Example.new
puts ex.foo
puts ex.bar
Adefine_method called in class method without proper receiver
BMissing parentheses in method call create_methods
CUsing string interpolation inside define_method block is invalid
DCannot pass multiple arguments to create_methods
Step-by-Step Solution
Solution:
  1. Step 1: Check where define_method is called

    define_method is called inside a class method without specifying receiver, so it tries to define class method but actually needs instance context.
  2. Step 2: Fix scope for define_method

    To define instance methods, define_method must be called on the class's singleton class or inside instance context.
  3. Final Answer:

    define_method called in class method without proper receiver -> Option A
  4. Quick Check:

    define_method scope error = class method context [OK]
Quick Trick: Call define_method on class's instance context, not directly in class method [OK]
Common Mistakes:
  • Assuming define_method works anywhere without receiver
  • Thinking string interpolation is invalid in blocks
  • Believing multiple arguments cause error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes