class_eval?class Dog def speak "woof" end end Dog.class_eval do def speak "bark" end end puts Dog.new.speak
The class_eval block redefines the speak method for the Dog class. So calling Dog.new.speak returns "bark" instead of the original "woof".
instance_eval on an object?class Cat def speak "meow" end end cat = Cat.new cat.instance_eval do def speak "purr" end end puts cat.speak
The instance_eval block defines a singleton method speak on the cat object, overriding the original speak method from the Cat class for this instance. So cat.speak calls the new method and prints "purr".
instance_eval not change the method for all instances of the class?class Bird def fly "I can fly" end end bird1 = Bird.new bird2 = Bird.new bird1.instance_eval do def fly "I cannot fly" end end puts bird1.fly puts bird2.fly
instance_eval defines methods on the singleton class of the specific object (bird1), so only bird1 has the new fly method. Other instances like bird2 use the original class method.
class_eval to add a class method?class Fish end Fish.class_eval do def self.swim "swimming" end end puts Fish.swim
The class_eval block adds a class method swim to the Fish class. Calling Fish.swim returns "swimming".
instance_eval to access instance variables?class Person def initialize(name) @name = name end end person = Person.new("Alice") result = person.instance_eval do @name + " Smith" end puts result
The instance_eval block runs inside the person object context, so it can access @name directly. It returns "Alice Smith".
