Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Advanced Metaprogramming

What will be the output of this Ruby code?

module M
  module_eval 'def shout; "Hey!"; end'
end

class C
  include M
end

puts C.new.shout
AHey
BNoMethodError
CRuntimeError
DHey!
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method definition with string in module_eval

    The method shout is defined inside module M using a string passed to module_eval.

  2. Step 2: Check class inclusion and method call

    Class C includes M, so C.new.shout calls the method and prints "Hey!".

  3. Final Answer:

    Hey! -> Option D
  4. Quick Check:

    String eval method call = Hey! [OK]
Quick Trick: String code in module_eval defines methods usable after include [OK]
Common Mistakes:
  • Missing exclamation mark in output
  • Expecting NoMethodError
  • Confusing with runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes