0
0
Rubyprogramming~5 mins

Each as the primary iterator in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Each as the primary iterator
O(n)
Understanding Time Complexity

When we use each to go through items in a list, it's important to know how the time it takes grows as the list gets bigger.

We want to find out how the number of steps changes when the list size changes.

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 goes through every item in the list once.
  • How many times: It runs exactly as many times as there are items in the list.
How Execution Grows With Input

As the list gets bigger, the number of steps grows in a straight line with it.

Input Size (n)Approx. Operations
1010 steps (one per item)
100100 steps
10001000 steps

Pattern observation: Doubling the list size doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows directly in proportion to the number of items in the list.

Common Mistake

[X] Wrong: "Using each is always slow because it loops over everything multiple times."

[OK] Correct: Actually, each goes through the list only once, so it's as fast as it can be for checking every item.

Interview Connect

Understanding how each works helps you explain how your code handles lists efficiently, a skill that shows you know how to think about performance.

Self-Check

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