Implicit return (last expression) in Ruby - Time & Space Complexity
Let's see how the time it takes to run a Ruby method depends on what it does inside.
We want to know how the method's steps grow as the input changes.
Analyze the time complexity of the following code snippet.
def sum_array(arr)
total = 0
arr.each do |num|
total += num
end
total
end
This method adds up all numbers in an array and returns the total using implicit return of the last expression.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array.
- How many times: Once for every item in the array.
As the array gets bigger, the method does more additions, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Since the method returns the last line, it runs only once regardless of input size."
[OK] Correct: The last line is just the result, but the loop before it runs once for each item, so the total work depends on input size.
Understanding how loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the loop with a recursive call? How would the time complexity change?"