Each as the primary iterator in Ruby - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
eachloop goes through every item in the list once. - How many times: It runs exactly as many times as there are items in the list.
As the list gets bigger, the number of steps grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps (one per item) |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the list size doubles the work done.
Time Complexity: O(n)
This means the time it takes grows directly in proportion to the number of items in the list.
[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.
Understanding how each works helps you explain how your code handles lists efficiently, a skill that shows you know how to think about performance.
"What if we nested one each loop inside another? How would the time complexity change?"