Raise for throwing errors in Ruby - Time & Space Complexity
When using raise to throw errors in Ruby, it is important to understand how this affects the program's running time.
We want to see how the time to run the code changes as the input size grows, especially when errors might be raised.
Analyze the time complexity of the following code snippet.
def check_numbers(numbers)
numbers.each do |num|
raise "Negative number found!" if num < 0
end
"All numbers are non-negative"
end
This code goes through a list of numbers and raises an error if it finds any negative number.
- Primary operation: Looping through each number in the list.
- How many times: Up to once for each number until a negative is found or the list ends.
The code checks each number one by one. If no negative number is found, it looks at all numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the number of items.
Time Complexity: O(n)
This means the time to run grows linearly with the number of items in the list.
[X] Wrong: "Raising an error makes the code run slower for all inputs."
[OK] Correct: Raising an error only happens when a problem is found, so it stops the loop early and can actually save time.
Understanding how error handling affects time helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we changed the code to collect all negative numbers before raising an error? How would the time complexity change?"