Class_eval and instance_eval in Ruby - Time & Space Complexity
When using class_eval and instance_eval, it's important to understand how the time to run these methods grows as the code inside them gets bigger.
We want to know how the number of operations changes when we evaluate code blocks on classes or objects.
Analyze the time complexity of the following code snippet.
class MyClass
def self.add_methods(n)
n.times do |i|
class_eval do
define_method("method_#{i}") { i }
end
end
end
end
MyClass.add_methods(5)
This code adds n methods to a class using class_eval inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that runs
ntimes, each time callingclass_evalto define a method. - How many times: Exactly
ntimes, once per method added.
Each time we increase n, the number of method definitions grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method definitions |
| 100 | 100 method definitions |
| 1000 | 1000 method definitions |
Pattern observation: The work grows directly with n. Doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of methods you add.
[X] Wrong: "Using class_eval or instance_eval runs instantly no matter how many times."
[OK] Correct: Each time you evaluate code, Ruby runs that code, so more code means more time. The cost adds up with each method defined.
Understanding how dynamic code evaluation scales helps you write efficient Ruby code and explain your reasoning clearly in interviews.
"What if we replaced class_eval with a single class_eval block that defines all methods inside it? How would the time complexity change?"