Bird
0
0

Identify the problem in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Advanced Metaprogramming
Identify the problem in this Ruby code:
class User
  def initialize(name)
    @name = name
  end
end

user = User.new('Alice')
user.instance_eval do
  def greet
    "Hello, #{@name}!"
  end
end
puts user.greet
Auser.greet will raise NoMethodError
Bgreet method cannot access @name instance variable
Cinstance_eval block syntax is incorrect
Dgreet method is defined on singleton class, so user.greet works fine
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance_eval on object

    The block defines method greet on the singleton class of user, so user.greet is valid.
  2. Step 2: Check access to instance variables

    Inside greet, @name is accessible because it's the same object.
  3. Final Answer:

    greet method is defined on singleton class, so user.greet works fine -> Option D
  4. Quick Check:

    instance_eval defines singleton methods = greet method is defined on singleton class, so user.greet works fine [OK]
Quick Trick: instance_eval defines singleton methods accessible on object [OK]
Common Mistakes:
  • Thinking instance variables inaccessible inside instance_eval method
  • Confusing block syntax
  • Expecting NoMethodError for greet

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes