Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Advanced Metaprogramming

What will be the output of the following Ruby code?

module M
  module_eval do
    def hello
      'Hello from M'
    end
  end
end

class C
  include M
end

puts C.new.hello
AHello from M
BNoMethodError
CSyntaxError
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand method definition inside module_eval

    The method hello is defined inside module M using module_eval, so it becomes an instance method of M.
  2. Step 2: Check class inclusion and method call

    Class C includes M, so instances of C have hello method. Calling C.new.hello returns 'Hello from M'.
  3. Final Answer:

    Hello from M -> Option A
  4. Quick Check:

    module_eval defines method, include makes it accessible = D [OK]
Quick Trick: module_eval defines methods accessible after include [OK]
Common Mistakes:
  • Assuming method is not defined
  • Confusing module_eval with class_eval
  • Expecting syntax error from block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes