0
0
Rubyprogramming~5 mins

Class_eval and instance_eval in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Class_eval and instance_eval
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that runs n times, each time calling class_eval to define a method.
  • How many times: Exactly n times, once per method added.
How Execution Grows With Input

Each time we increase n, the number of method definitions grows linearly.

Input Size (n)Approx. Operations
1010 method definitions
100100 method definitions
10001000 method definitions

Pattern observation: The work grows directly with n. Doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of methods you add.

Common Mistake

[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.

Interview Connect

Understanding how dynamic code evaluation scales helps you write efficient Ruby code and explain your reasoning clearly in interviews.

Self-Check

"What if we replaced class_eval with a single class_eval block that defines all methods inside it? How would the time complexity change?"