Send for calling methods dynamically in Ruby - Time & Space Complexity
When we use send in Ruby to call methods dynamically, it is important to understand how this affects the time it takes to run the program.
We want to know how the number of method calls grows as we call more methods dynamically.
Analyze the time complexity of the following code snippet.
class Greeter
def hello
"Hello!"
end
def goodbye
"Goodbye!"
end
end
g = Greeter.new
methods = [:hello, :goodbye]
methods.each { |m| puts g.send(m) }
This code calls methods dynamically on an object using send inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
sendto invoke a method dynamically. - How many times: Once for each method symbol in the
methodsarray.
Each method call happens once per item in the list of method names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls via send |
| 100 | 100 method calls via send |
| 1000 | 1000 method calls via send |
Pattern observation: The number of dynamic calls grows directly with the number of methods to call.
Time Complexity: O(n)
This means the time to run grows linearly with the number of methods called dynamically.
[X] Wrong: "Using send makes the code slower in a way that changes the overall time complexity."
[OK] Correct: Calling methods dynamically with send adds a small fixed overhead per call but does not change how the total time grows with the number of calls.
Understanding how dynamic method calls scale helps you explain your code's performance clearly and confidently in real projects or interviews.
What if we replaced the array of method names with a nested loop calling send multiple times per method? How would the time complexity change?