0
0
Rubyprogramming~7 mins

Class_eval and instance_eval in Ruby

Choose your learning style9 modes available
Introduction

These methods let you add or change code inside a class or an object while the program is running. It helps you customize behavior without changing the original code.

You want to add new methods to a class after it is created.
You need to change or add behavior to a single object only.
You want to run code in the context of a class or object to access its private parts.
You are writing a library or tool that modifies other code dynamically.
You want to test or debug by injecting methods or variables temporarily.
Syntax
Ruby
ClassName.class_eval do
  # code to add or change instance methods or variables
end

object.instance_eval do
  # code to add or change methods or variables for this object only
end

class_eval runs code inside the class context, affecting all instances.

instance_eval runs code inside a single object, affecting only that object.

Examples
Adds a method greet to the Person class using class_eval. All Person objects can use it.
Ruby
class Person
end

Person.class_eval do
  def greet
    "Hello!"
  end
end

p = Person.new
puts p.greet
Adds a method shout only to the str object using instance_eval. Other strings won't have it.
Ruby
str = "hello"

str.instance_eval do
  def shout
    upcase + "!"
  end
end

puts str.shout
Changes the existing speak method for all Dog objects by reopening the class with class_eval.
Ruby
class Dog
  def speak
    "woof"
  end
end

Dog.class_eval do
  def speak
    "bark"
  end
end

puts Dog.new.speak
Sample Program

This program adds a start method to the Car class using class_eval. So all cars can start.

Then it adds a turbo_boost method only to the car1 object using instance_eval. car2 does not have this method.

Ruby
class Car
end

Car.class_eval do
  def start
    "Car started"
  end
end

car1 = Car.new
car2 = Car.new

puts car1.start

car1.instance_eval do
  def turbo_boost
    "Turbo boost activated!"
  end
end

puts car1.turbo_boost

# car2.turbo_boost # This would cause an error because car2 does not have this method
OutputSuccess
Important Notes

Use class_eval to change or add methods for all instances of a class.

Use instance_eval to add or change methods for a single object only.

Be careful: changing classes or objects at runtime can make code harder to understand.

Summary

class_eval changes the class itself and affects all its objects.

instance_eval changes only one object, not the whole class.

Both help you add or change code while the program runs.