0
0
Rubyprogramming~5 mins

Prepend for method chain insertion in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Prepend for method chain insertion
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops, recursion, or repeated calls.

  • Primary operation: Calling the process method which triggers the prepended methods in order.
  • How many times: Each prepended method runs once per process call, chaining through all prepended modules.
How Execution Grows With Input

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
12 (1 prepended + original)
56 (5 prepended + original)
1011 (10 prepended + original)

Pattern observation: The work grows linearly as more methods are prepended.

Final Time Complexity

Time Complexity: O(n)

This means the time to run process grows directly with the number of prepended methods.

Common Mistake

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

Interview Connect

Understanding how method chains grow helps you reason about code efficiency and design in real projects.

Self-Check

What if we replaced prepend with append (using include)? How would the time complexity of process change?