Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Advanced Metaprogramming
What will be the output of this Ruby code?
class Greeter
  def initialize(name)
    @name = name
    define_method(:greet) { "Hello, #{@name}!" }
  end
end

g = Greeter.new('Alice')
puts g.greet
AHello, @name!
BHello, Alice!
CError: undefined method greet
DHello, !
Step-by-Step Solution
Solution:
  1. Step 1: Understand define_method with closure

    The block captures @name from the instance, so it uses 'Alice' when greet is called.
  2. Step 2: Check output of puts g.greet

    It prints "Hello, Alice!" because @name is 'Alice'.
  3. Final Answer:

    Hello, Alice! -> Option B
  4. Quick Check:

    Closure captures @name = 'Alice' [OK]
Quick Trick: define_method block remembers instance variables [OK]
Common Mistakes:
  • Expecting literal '@name' output
  • Thinking method is undefined
  • Ignoring closure capture

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes