Define_method with closures in Ruby - Time & Space Complexity
We want to understand how the time it takes to create methods using define_method with closures changes as we add more methods.
How does the number of methods affect the work done when defining them?
Analyze the time complexity of the following code snippet.
class Greeter
def initialize(names)
names.each do |name|
self.class.define_method("greet_#{name}") do
"Hello, #{name}!"
end
end
end
end
Greeter.new(["alice", "bob", "carol"])
This code creates a new method for each name in the list, using closures to remember each name.
- Primary operation: Looping over the list of names to define methods.
- How many times: Once for each name in the input list.
Each new name adds one more method definition, so the work grows directly with the number of names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method definitions |
| 100 | 100 method definitions |
| 1000 | 1000 method definitions |
Pattern observation: The work grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to define methods grows directly in proportion to the number of names.
[X] Wrong: "Defining methods with closures happens instantly, no matter how many methods we add."
[OK] Correct: Each method definition takes some time, so more methods mean more work overall.
Understanding how loops and method definitions scale helps you explain how your code behaves with bigger inputs, a skill useful in many programming tasks.
What if we changed the code to define methods inside a nested loop? How would the time complexity change?