Bird
0
0

Identify the error in the following code snippet:

medium📝 Debug Q14 of 15
Ruby - Advanced Metaprogramming

Identify the error in the following code snippet:

module M
  module_eval 'def greet; puts "Hi" end'
end

class C
  include M
end

C.new.greet
AThe method greet is defined but calling it prints nothing.
BNo error; code runs and prints 'Hi'.
CSyntax error due to missing semicolon in module_eval string.
DNoMethodError because greet is not defined as an instance method.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze module_eval string syntax

    The string passed to module_eval defines method greet correctly with a semicolon separating statements.
  2. Step 2: Check method availability and call

    Class C includes M, so greet is available to instances. Calling C.new.greet prints 'Hi'.
  3. Final Answer:

    No error; code runs and prints 'Hi'. -> Option B
  4. Quick Check:

    module_eval string defines method correctly = C [OK]
Quick Trick: Check string syntax carefully; semicolon separates statements [OK]
Common Mistakes:
  • Thinking semicolon is missing
  • Assuming greet is not instance method
  • Expecting runtime error from string eval

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes