Bird
0
0

What does class_eval do when called on a Ruby class?

easy📝 Conceptual Q1 of 15
Ruby - Advanced Metaprogramming
What does class_eval do when called on a Ruby class?
AIt evaluates code in the context of an instance of the class, modifying instance variables only.
BIt creates a new subclass of the class dynamically.
CIt evaluates code in the context of the class, allowing modification of class methods and variables.
DIt runs code outside the class context without modifying it.
Step-by-Step Solution
Solution:
  1. Step 1: Understand class_eval context

    class_eval runs code inside the class context, so it can add or change methods and variables of the class itself.
  2. Step 2: Compare with instance context

    Unlike instance_eval, which runs code in an instance context, class_eval affects the class level.
  3. Final Answer:

    It evaluates code in the context of the class, allowing modification of class methods and variables. -> Option C
  4. Quick Check:

    class_eval = class context [OK]
Quick Trick: class_eval changes class methods; instance_eval changes instance context [OK]
Common Mistakes:
  • Confusing instance_eval with class_eval context
  • Thinking class_eval creates subclasses
  • Assuming class_eval runs outside class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes