Module_eval for dynamic behavior in Ruby - Time & Space Complexity
We want to understand how the time it takes to run code changes when using module_eval to add methods dynamically.
How does the cost grow when we add more methods this way?
Analyze the time complexity of the following code snippet.
module MyModule
def self.add_methods(n)
n.times do |i|
module_eval do
define_method("method_#{i}") { i }
end
end
end
end
MyModule.add_methods(5)
This code adds n methods dynamically to a module using module_eval.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop runs
ntimes, each time callingmodule_evalto define a method. - How many times: Exactly
ntimes, once per method added.
Each new method requires running module_eval once, so the total work grows as we add more methods.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 module_eval calls |
| 100 | About 100 module_eval calls |
| 1000 | About 1000 module_eval calls |
Pattern observation: The work grows directly with the number of methods added.
Time Complexity: O(n)
This means the time to add methods grows in a straight line as you add more methods.
[X] Wrong: "Using module_eval once to add many methods is always faster than calling it multiple times."
[OK] Correct: Each module_eval call runs code, so calling it many times adds up linearly. Using it once with many method definitions can be more efficient.
Understanding how dynamic code execution scales helps you write flexible Ruby code that stays efficient as it grows.
What if we changed the code to call module_eval once with all method definitions inside? How would the time complexity change?