Break, next, and redo behavior in Ruby - Time & Space Complexity
When using break, next, and redo in loops, the number of times the loop runs can change.
We want to see how these commands affect how long the code takes as the input grows.
Analyze the time complexity of the following code snippet.
arr = [1, 2, 3, 4, 5]
arr.each do |num|
redo_count ||= 0
redo_count += 1
next if num.even?
puts num
break if num >= arr.size
redo if redo_count < 2 && num == 1
end
This code loops over an array, skips even numbers, prints odd numbers, stops if the number is greater than or equal to the array size, and repeats the first number once more.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the array elements with
each. - How many times: Normally once per element, but
redorepeats the current element, andbreakcan stop early.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times, plus any redo repeats |
| 100 | About 100 times, plus redo repeats |
| 1000 | About 1000 times, plus redo repeats |
Pattern observation: The loop mostly runs once per item, but redo can add a few repeats, and break can stop early, so time grows roughly with input size.
Time Complexity: O(n)
This means the time grows roughly in direct proportion to the number of items in the input.
[X] Wrong: "Using redo makes the loop run forever and time complexity is infinite."
[OK] Correct: Redo repeats the current step but only when triggered by a condition; it does not always cause infinite loops if used carefully.
Understanding how break, next, and redo affect loops helps you explain how your code runs and how efficient it is.
"What if we removed the break statement? How would the time complexity change?"