Why methods always return a value in Ruby - Performance Analysis
When we look at Ruby methods, they always give back a result. Understanding how this affects the time it takes to run helps us write better code.
We want to see how the work done inside a method grows as the input changes.
Analyze the time complexity of the following code snippet.
def sum_array(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
This method adds up all numbers in an array and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the input array.
As the array gets bigger, the method does more additions, one for each number.
| 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. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The method returns instantly because it just returns a value."
[OK] Correct: Even though a method returns a value, it still does all the work inside first, which takes time depending on input size.
Knowing how method return values relate to the work done inside helps you explain code efficiency clearly and confidently.
"What if we changed the method to return the sum of only the first half of the array? How would the time complexity change?"