0
0
Rubyprogramming~5 mins

Each for iteration in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Each for iteration
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a Ruby each loop changes as the list gets bigger.

How does the number of steps grow when we use each to go through items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
  puts num * 2
end

This code goes through each number in the list and prints double its value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The each loop runs once for every item in the list.
  • How many times: Exactly as many times as there are items in the array.
How Execution Grows With Input

As the list gets bigger, the number of times the loop runs grows the same way.

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

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 number of items.

Common Mistake

[X] Wrong: "The each loop runs a fixed number of times no matter the list size."

[OK] Correct: The loop runs once for every item, so if the list grows, the loop runs more times.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs handle bigger data.

Self-Check

"What if we nested one each loop inside another? How would the time complexity change?"