0
0
Rubyprogramming~5 mins

Method chaining patterns in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method chaining patterns
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each method processes the whole list, so time grows with list size.

Input Size (n)Approx. Operations
10About 30 (3 passes over 10 items)
100About 300 (3 passes over 100 items)
1000About 3000 (3 passes over 1000 items)

Pattern observation: Operations increase roughly in direct proportion to input size.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of items processed.

Common Mistake

[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.

Interview Connect

Understanding how method chaining affects time helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if the methods were combined into one that does all steps in a single pass? How would the time complexity change?"