0
0
Rubyprogramming~20 mins

Class_eval and instance_eval in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Eval Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
ANoMethodError
Bwoof
Cnil
Dbark
Attempts:
2 left
💡 Hint
class_eval changes methods inside the class context.
Predict Output
intermediate
2: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
ANoMethodError
Bpurr
Cmeow
Dnil
Attempts:
2 left
💡 Hint
instance_eval changes the singleton class of the object.
🔧 Debug
advanced
2: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
Ainstance_eval defines method only on bird1's singleton class, not Bird class
Binstance_eval changes the Bird class method for all instances
Cinstance_eval raises an error when redefining methods
Dinstance_eval modifies the superclass methods
Attempts:
2 left
💡 Hint
Think about what singleton class means for an object.
Predict Output
advanced
2: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
Aswimming
BNoMethodError
Cnil
DSyntaxError
Attempts:
2 left
💡 Hint
class_eval can add class methods using self.method_name syntax.
Predict Output
expert
3: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
ANoMethodError
BAlice Smith
Cnil
DNameError
Attempts:
2 left
💡 Hint
instance_eval runs the block in the context of the object, so it can access instance variables.