0
0
Rubyprogramming~5 mins

Implicit return (last expression) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Implicit return (last expression)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the method does more additions, one for each item.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how loops affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the loop with a recursive call? How would the time complexity change?"