Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
Ruby - Advanced Metaprogramming
Identify the error in this code snippet:
class Cat
end

kitty = Cat.new
kitty.class_eval { def meow; 'Meow!'; end }
puts kitty.meow
ANo error; outputs 'Meow!'
BNoMethodError because class_eval is called on instance
CSyntaxError due to missing block
DRuntimeError because method already exists
Step-by-Step Solution
Solution:
  1. Step 1: Check receiver of class_eval

    class_eval is a method of Class, not of instances; calling it on an instance raises NoMethodError.
  2. Step 2: Verify execution

    Since kitty is an instance, kitty.class_eval raises NoMethodError; thus, puts kitty.meow is not reached.
  3. Final Answer:

    NoMethodError because class_eval is called on instance -> Option B
  4. Quick Check:

    class_eval is a Class method, not instance method [OK]
Quick Trick: class_eval is called on classes, not instances [OK]
Common Mistakes:
  • Thinking class_eval can be called on instances
  • Expecting NoMethodError for instance.class_eval
  • Confusing class_eval usage with class-only restriction

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes