0
0
Rubyprogramming~5 mins

Open classes (reopening classes) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Open classes (reopening classes)
O(n)
Understanding Time Complexity

When we reopen a class in Ruby to add or change methods, it's important to see how this affects the program's speed.

We want to know how the time to run the program changes as we add more code inside the reopened class.

Scenario Under Consideration

Analyze the time complexity of reopening a class and adding a method that loops through an array.


class Calculator
  def sum(numbers)
    total = 0
    numbers.each do |num|
      total += num
    end
    total
  end
end

class Calculator
  def multiply(numbers)
    product = 1
    numbers.each do |num|
      product *= num
    end
    product
  end
end
    

This code reopens the Calculator class to add a multiply method that loops through an array.

Identify Repeating Operations

Look at the loops inside each method.

  • Primary operation: Looping through the array with each to process numbers.
  • How many times: Once for each element in the input array.
How Execution Grows With Input

As the array gets bigger, the number of steps grows in a straight line.

Input Size (n)Approx. Operations
10About 10 steps
100About 100 steps
1000About 1000 steps

Pattern observation: The work grows directly with the size of the input array.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the method grows in a straight line as the input gets bigger.

Common Mistake

[X] Wrong: "Reopening a class adds extra loops that multiply the time complexity."

[OK] Correct: Each method runs separately, so reopening a class doesn't multiply loops; it just adds new methods.

Interview Connect

Understanding how reopening classes affects performance helps you write clear and efficient Ruby code, a skill that shows you know how to manage program behavior and speed.

Self-Check

What if the multiply method called the sum method inside its loop? How would the time complexity change?