Define_method for dynamic methods in Ruby - Time & Space Complexity
We want to understand how the time it takes to create dynamic methods changes as we add more methods.
How does the work grow when we define many methods using define_method?
Analyze the time complexity of the following code snippet.
class DynamicMethods
def initialize(names)
names.each do |name|
self.class.define_method(name) do
"Hello from #{name}!"
end
end
end
end
obj = DynamicMethods.new([:greet, :welcome, :hello])
This code creates methods dynamically for each name in the list.
- Primary operation: Looping over the list of names to define methods.
- How many times: Once for each name in the input list.
Each new method requires one step to define it, so the total work grows as we add more names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method definitions |
| 100 | 100 method definitions |
| 1000 | 1000 method definitions |
Pattern observation: The work grows directly with the number of methods we create.
Time Complexity: O(n)
This means the time to define methods grows in a straight line with the number of methods.
[X] Wrong: "Defining methods with define_method is instant no matter how many methods."
[OK] Correct: Each method takes some time to create, so more methods mean more total time.
Understanding how dynamic method creation scales helps you write flexible code that stays efficient as it grows.
"What if we defined methods inside a nested loop? How would that affect the time complexity?"