Prepend for method chain insertion in Ruby - Time & Space Complexity
We want to understand how adding a method at the start of a chain affects the time it takes to run.
How does inserting a method at the beginning change the work done as the chain grows?
Analyze the time complexity of the following Ruby code snippet.
class StringProcessor
def initialize(str)
@str = str
end
def upcase
@str = @str.upcase
self
end
def reverse
@str = @str.reverse
self
end
def prepend_method(new_method)
self.singleton_class.prepend(Module.new do
define_method(:process) do
send(new_method)
super()
end
end)
end
def process
@str
end
end
processor = StringProcessor.new("hello")
processor.prepend_method(:upcase)
processor.prepend_method(:reverse)
result = processor.process
This code adds methods at the start of a method chain using prepend, changing how process works.
Look for loops, recursion, or repeated calls.
- Primary operation: Calling the
processmethod which triggers the prepended methods in order. - How many times: Each prepended method runs once per
processcall, chaining through all prepended modules.
Each time we add a new method with prepend, the process call runs one more method before the original.
| Number of prepended methods (n) | Approx. Operations per process call |
|---|---|
| 1 | 2 (1 prepended + original) |
| 5 | 6 (5 prepended + original) |
| 10 | 11 (10 prepended + original) |
Pattern observation: The work grows linearly as more methods are prepended.
Time Complexity: O(n)
This means the time to run process grows directly with the number of prepended methods.
[X] Wrong: "Adding more prepended methods won't affect how long process takes."
[OK] Correct: Each prepended method adds one more step to run, so more prepends mean more work.
Understanding how method chains grow helps you reason about code efficiency and design in real projects.
What if we replaced prepend with append (using include)? How would the time complexity of process change?