Recall & Review
beginner
What does
class_eval do in Ruby?<p><code>class_eval</code> runs code inside the context of a class. It lets you add methods or change the class from outside.</p>Click to reveal answer
intermediate
What is the difference between
class_eval and instance_eval?class_eval runs code as if inside the class (affects all instances). instance_eval runs code in the context of a single object (affects only that object).
Click to reveal answer
beginner
How does
instance_eval affect an object?instance_eval changes or adds methods and variables only for that one object, not the whole class.
Click to reveal answer
beginner
Give a simple example of using
class_eval to add a method.<pre>class MyClass; end
MyClass.class_eval do
def greet
"Hello!"
end
end
obj = MyClass.new
puts obj.greet # Outputs: Hello!</pre>Click to reveal answer
intermediate
Why use
instance_eval instead of normal method definition?Use instance_eval to add or change methods on a single object without affecting other objects of the same class.
Click to reveal answer
What does
class_eval change in Ruby?✗ Incorrect
class_eval runs code inside the class context, affecting the class and all its instances.
Which method runs code in the context of a single object?
✗ Incorrect
instance_eval runs code on a single object, changing only that object.
If you want to add a method to all instances of a class, which should you use?
✗ Incorrect
class_eval adds methods to the class, so all instances get them.
What is a key use of
instance_eval?✗ Incorrect
instance_eval lets you add or change methods on just one object.
Which of these is true about
class_eval?✗ Incorrect
class_eval is used to add or change instance methods inside a class.
Explain in your own words how
class_eval and instance_eval differ in Ruby.Think about whether the change affects many objects or just one.
You got /3 concepts.
Describe a situation where you would use
instance_eval instead of normal method definition.Imagine you want one special object to behave differently.
You got /3 concepts.