Pipeline operator concept in Ruby - Time & Space Complexity
We want to understand how the time it takes to run code with the pipeline operator changes as the input grows.
Specifically, we ask: how does chaining operations affect the total work done?
Analyze the time complexity of the following code snippet.
numbers = (1..n).to_a
result = numbers
.map { |x| x * 2 }
.select { |x| x % 3 == 0 }
.reduce(0) { |sum, x| sum + x }
This code doubles each number, keeps only those divisible by 3, then sums them all.
Look at the repeated steps in the code.
- Primary operation: The
mapandselecteach go through all numbers once. - How many times: Each step loops over the entire list of size
nonce.
As the list gets bigger, each step takes longer because it looks at every item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 steps (3 passes over 10 items) |
| 100 | About 300 steps (3 passes over 100 items) |
| 1000 | About 3000 steps (3 passes over 1000 items) |
Pattern observation: The total work grows roughly in a straight line with the input size, multiplied by the number of chained steps.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items in the list.
[X] Wrong: "Using multiple chained steps with the pipeline operator makes the code run much slower, like multiplying time by n each time."
[OK] Correct: Each step looks at all items once, so total time adds up linearly, not exponentially. The pipeline just chains simple passes.
Understanding how chaining operations affects time helps you write clear code that also runs efficiently. This skill shows you can think about both style and speed.
What if we replaced map and select with a single loop doing both steps together? How would the time complexity change?