0
0
Rubyprogramming~5 mins

Begin/rescue/end blocks in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Begin/rescue/end blocks
O(n)
Understanding Time Complexity

When we use begin/rescue/end blocks in Ruby, we want to know how the time to run the code changes as the input grows.

We ask: How much extra time does handling errors add when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


begin
  numbers = [1, 2, 3, 4, 5]
  total = 0
  numbers.each do |num|
    total += 10 / num
  end
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
end
    

This code sums 10 divided by each number in an array, and handles division by zero errors if they occur.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array with each.
  • How many times: Once for every element in the array (n times).
How Execution Grows With Input

As the array gets bigger, the number of divisions and additions grows in a straight line.

Input Size (n)Approx. Operations
10About 10 divisions and additions
100About 100 divisions and additions
1000About 1000 divisions and additions

Pattern observation: The work grows evenly as the input grows; doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in direct proportion to the number of items in the array.

Common Mistake

[X] Wrong: "The rescue block makes the whole code run slower for every item in the array."

[OK] Correct: The rescue block only runs if an error happens. If no error occurs, it does not slow down the loop itself.

Interview Connect

Understanding how error handling affects time helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if the rescue block handled errors inside the loop instead of outside? How would the time complexity change?"