Open classes (reopening classes) in Ruby - Time & Space 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.
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.
Look at the loops inside each method.
- Primary operation: Looping through the array with
eachto process numbers. - How many times: Once for each element in the input array.
As the array gets bigger, the number of steps grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to run the method grows in a straight line as the input gets bigger.
[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.
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.
What if the multiply method called the sum method inside its loop? How would the time complexity change?