0
0
Rubyprogramming~3 mins

Why Class_eval and instance_eval in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change how your program works while it's running, without stopping or rewriting everything?

The Scenario

Imagine you have a class in Ruby, and you want to add or change methods while your program is running. Doing this by rewriting the whole class or creating many subclasses can be confusing and slow.

The Problem

Manually changing classes or objects means stopping your program, editing code, and restarting. This is slow and error-prone. You might accidentally break things or create many copies of similar code.

The Solution

Using class_eval and instance_eval lets you add or change methods directly inside a class or an object while the program runs. This makes your code flexible and powerful without rewriting or restarting.

Before vs After
Before
class Dog
  def bark
    puts 'Woof!'
  end
end

# To add a new method, you must reopen the class manually
After
Dog.class_eval do
  def wag_tail
    puts 'Wagging tail'
  end
end

# Adds method dynamically without reopening class manually
What It Enables

You can change or add behavior to classes and objects on the fly, making your Ruby programs more dynamic and adaptable.

Real Life Example

In a web app, you might want to add logging or debugging methods to certain objects only when needed, without changing the original class code or restarting the app.

Key Takeaways

class_eval changes or adds methods inside a class dynamically.

instance_eval changes or adds methods or variables inside a single object.

Both help make Ruby programs flexible and easier to maintain.