Challenge - 5 Problems
Ruby Eval Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of class_eval modifying a class
What is the output of this Ruby code using
class_eval?Ruby
class Dog def speak "woof" end end Dog.class_eval do def speak "bark" end end puts Dog.new.speak
Attempts:
2 left
💡 Hint
class_eval changes methods inside the class context.
✗ Incorrect
The class_eval block redefines the speak method for the Dog class. So calling Dog.new.speak returns "bark" instead of the original "woof".
❓ Predict Output
intermediate2:00remaining
Output of instance_eval on an object
What does this Ruby code print when using
instance_eval on an object?Ruby
class Cat def speak "meow" end end cat = Cat.new cat.instance_eval do def speak "purr" end end puts cat.speak
Attempts:
2 left
💡 Hint
instance_eval changes the singleton class of the object.
✗ Incorrect
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".
🔧 Debug
advanced2:30remaining
Why does instance_eval not override method for all instances?
Given this code, why does
instance_eval not change the method for all instances of the class?Ruby
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
Attempts:
2 left
💡 Hint
Think about what singleton class means for an object.
✗ Incorrect
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.
❓ Predict Output
advanced2:00remaining
Output of class_eval adding a class method
What is the output of this Ruby code that uses
class_eval to add a class method?Ruby
class Fish end Fish.class_eval do def self.swim "swimming" end end puts Fish.swim
Attempts:
2 left
💡 Hint
class_eval can add class methods using self.method_name syntax.
✗ Incorrect
The class_eval block adds a class method swim to the Fish class. Calling Fish.swim returns "swimming".
❓ Predict Output
expert3:00remaining
Output of instance_eval with block accessing instance variables
What is the output of this Ruby code using
instance_eval to access instance variables?Ruby
class Person def initialize(name) @name = name end end person = Person.new("Alice") result = person.instance_eval do @name + " Smith" end puts result
Attempts:
2 left
💡 Hint
instance_eval runs the block in the context of the object, so it can access instance variables.
✗ Incorrect
The instance_eval block runs inside the person object context, so it can access @name directly. It returns "Alice Smith".