0
0
Rubyprogramming~5 mins

Class_eval and instance_eval in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AOnly one object instance
BThe superclass
CGlobal variables
DThe class itself and all its instances
Which method runs code in the context of a single object?
Ainstance_eval
Bclass_eval
Cmodule_eval
Deval
If you want to add a method to all instances of a class, which should you use?
Ainstance_eval
Bclass_eval
Cobject_eval
Dmethod_eval
What is a key use of instance_eval?
AAdd methods to a single object
BChange global constants
CCreate a new class
DChange the superclass
Which of these is true about class_eval?
AIt changes the value of local variables outside the class
BIt only works on objects, not classes
CIt can add instance methods to a class
DIt runs code in the global scope
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.