Introduction
These commands help control loops by deciding when to stop, skip, or repeat steps.
These commands help control loops by deciding when to stop, skip, or repeat steps.
break next redo
break stops the whole loop immediately.
next skips to the next loop cycle.
redo repeats the current loop step without checking the loop condition again.
for i in 1..5 break if i > 3 puts i end
for i in 1..5 next if i == 3 puts i end
for i in 1..5 puts i redo if i == 2 end
This program shows how next skips printing 3, redo repeats printing 4, and break stops the loop at 5.
repeat_count = 0 for i in 1..5 if i == 3 puts "Skipping 3" next elsif i == 4 puts "Repeating 4" repeat_count += 1 redo if repeat_count < 5 elsif i == 5 puts "Stopping at 5" break else puts i end end
redo repeats the current loop step without checking the loop condition again.
Use break to exit loops early to save time or avoid errors.
next is useful to skip unwanted steps but keep looping.
break stops the loop completely.
next skips to the next loop cycle.
redo repeats the current loop step.
break keyword do inside a Ruby loop?breakbreak keyword immediately stops the loop and exits it, no further iterations happen.next skips to the next iteration, redo repeats the current one, but break stops all looping.break = stop loop [OK]next is used in Ruby to skip the rest of the current loop iteration and move to the next one.break stops the loop, redo repeats the current iteration, and skip is not a Ruby keyword.i = 0
while i < 3
i += 1
if i == 2
redo
end
puts i
endi == 2, redo repeats the current iteration without incrementing i again, causing the loop to print 2 repeatedly.i is not changed inside the redo loop, it never moves past 2, causing an infinite loop printing 2 repeatedly.for i in 1..3
if i == 2
next
elsif i == 3
redo
end
puts i
endredo inside the elsif i == 3 causes the loop to repeat the same iteration infinitely because i does not change.next works fine in for loops, the if statement is properly closed, and puts can be after if.next and redo. Which code achieves this correctly?
i = 0
while i < 5
i += 1
if i == 3
# skip 3
elsif i == 4
# print 4 twice
end
puts i
endnext when i == 3 skips printing 3 and moves to next iteration.i == 4, print it once, then use redo to repeat the iteration and print 4 again.Pass the test and this pattern moves unknown