Variable-length arguments (*args) in Ruby - Time & Space Complexity
When a method accepts variable-length arguments, it can take many inputs at once. We want to understand how the time to run the method changes as the number of inputs grows.
How does the method's work grow when given more arguments?
Analyze the time complexity of the following code snippet.
def sum_all(*args)
total = 0
args.each do |num|
total += num
end
total
end
This method adds up all numbers passed to it, no matter how many.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each argument in
argsto add it tototal. - How many times: Once for each argument passed to the method.
Each new argument means one more addition operation. So if you double the number of inputs, you double the work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of inputs.
Time Complexity: O(n)
This means the time to run the method grows in a straight line with the number of arguments.
[X] Wrong: "Adding more arguments won't affect the time much because it's just one method call."
[OK] Correct: Each argument adds one step to the loop, so more arguments mean more work inside the method.
Understanding how variable arguments affect time helps you explain how your code scales. It shows you can think about efficiency even in simple methods.
"What if we changed the method to multiply all arguments instead of adding? How would the time complexity change?"