Method chaining patterns in Ruby - Time & Space Complexity
We want to understand how the time taken by method chaining changes as the input grows.
How does calling many methods one after another affect performance?
Analyze the time complexity of the following code snippet.
class NumberList
def initialize(numbers)
@numbers = numbers
end
def double
@numbers = @numbers.map { |n| n * 2 }
self
end
def select_even
@numbers = @numbers.select(&:even?)
self
end
def sum
@numbers.reduce(0, :+)
end
end
list = NumberList.new((1..1000).to_a)
result = list.double.select_even.sum
puts result
This code doubles numbers, selects even ones, then sums them, using method chaining.
Look for loops or repeated work inside each method.
- Primary operation: Each method uses array traversal (map, select, reduce).
- How many times: Each traversal goes through all elements once per method call.
Each method processes the whole list, so time grows with list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (3 passes over 10 items) |
| 100 | About 300 (3 passes over 100 items) |
| 1000 | About 3000 (3 passes over 1000 items) |
Pattern observation: Operations increase roughly in direct proportion to input size.
Time Complexity: O(n)
This means the time grows linearly with the number of items processed.
[X] Wrong: "Method chaining makes the code run faster because it looks shorter."
[OK] Correct: Each method still processes the whole list separately, so chaining can add up the work, not reduce it.
Understanding how method chaining affects time helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the methods were combined into one that does all steps in a single pass? How would the time complexity change?"