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?"
Practice
Solution
Step 1: Understand method chaining concept
Method chaining allows calling several methods one after another on the same object without repeating the object name.Step 2: Identify the main purpose
The main goal is to write shorter, cleaner code by linking method calls in one line.Final Answer:
To call multiple methods on the same object in one line -> Option AQuick Check:
Method chaining = calling multiple methods on one object [OK]
- Thinking it creates new objects automatically
- Confusing with threading or parallel execution
- Believing it converts objects to strings
Solution
Step 1: Recall Ruby method call syntax
In Ruby, methods are called on objects using dot notation: object.method.Step 2: Identify chaining syntax
Method chaining uses multiple dots to call methods one after another on the same object.Final Answer:
object.method1.method2.method3 -> Option BQuick Check:
Ruby chaining uses dots between methods [OK]
- Using arrows (->) which is not Ruby syntax
- Using double colons (::) which are for constants or modules
- Using pipes (|) which are not method call operators
class Box
def initialize(value)
@value = value
end
def add(x)
@value += x
self
end
def multiply(x)
@value *= x
self
end
def value
@value
end
end
box = Box.new(2)
result = box.add(3).multiply(4).value
puts resultSolution
Step 1: Trace the add method
Start with @value = 2. add(3) adds 3: 2 + 3 = 5, returns self.Step 2: Trace the multiply method
multiply(4) multiplies @value by 4: 5 * 4 = 20, returns self.Step 3: Call value method
value returns @value which is 20.Final Answer:
20 -> Option AQuick Check:
2 + 3 = 5; 5 * 4 = 20 [OK]
- Forgetting that add and multiply return self
- Calculating operations in wrong order
- Returning intermediate values instead of final
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, #{@name}!"
end
def farewell
puts "Goodbye, #{@name}!"
end
end
p = Person.new("Sam")
p.greet.farewellSolution
Step 1: Check method return values
greet prints a message but returns nil (default for puts).Step 2: Understand chaining requirement
For chaining, greet must return self to allow calling farewell next.Final Answer:
greet method does not return self, so chaining fails -> Option DQuick Check:
Method chaining needs methods to return self [OK]
- Assuming puts returns self
- Thinking initialize needs explicit return
- Believing object creation is the problem
TextFormatter that allows chaining methods to transform a string. The methods are:-
upcase: converts text to uppercase-
reverse: reverses the text-
append(str): adds str to the endWhich implementation correctly supports chaining all these methods and returns the final string with
result?Solution
Step 1: Understand chaining requirements
To chain methods, each must return self (the object) so next method can be called.Step 2: Provide final output method
Since methods return self, a separate method (like result) should return the final string.Final Answer:
Each method modifies @text, returns self; add aresultmethod returning @text -> Option CQuick Check:
Return self to chain, separate method to get final string [OK]
- Returning strings breaks chaining
- Printing inside methods returns nil
- Returning new objects breaks original chain
Ready to prove it?
Pass the test and this pattern moves unknown
