0
0
Rubyprogramming~5 mins

Why methods always return a value in Ruby - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why methods always return a value in Ruby
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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

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

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

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

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

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: "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.

Interview Connect

Knowing how method return values relate to the work done inside helps you explain code efficiency clearly and confidently.

Self-Check

"What if we changed the method to return the sum of only the first half of the array? How would the time complexity change?"