Class methods with self prefix in Ruby - Time & Space Complexity
We want to understand how long a class method with the self prefix takes to run as the input size grows.
How does the work inside such a method change when we give it bigger input?
Analyze the time complexity of the following code snippet.
class Calculator
def self.sum(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
end
This method adds up all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the input array.
As the list of numbers gets bigger, the method does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Class methods with self run instantly no matter the input size."
[OK] Correct: Even though it's a class method, if it loops through input, the time depends on how big the input is.
Knowing how class methods scale with input size helps you explain your code clearly and shows you understand efficiency.
"What if we changed the method to call itself recursively for each number? How would the time complexity change?"