0
0
Rubyprogramming~5 mins

Break, next, and redo behavior in Ruby

Choose your learning style9 modes available
Introduction

These commands help control loops by deciding when to stop, skip, or repeat steps.

Stop a loop early when a condition is met.
Skip the current step and move to the next one in a loop.
Repeat the current step again without moving forward.
Syntax
Ruby
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.

Examples
Stops printing numbers after 3.
Ruby
for i in 1..5
  break if i > 3
  puts i
end
Skips printing number 3.
Ruby
for i in 1..5
  next if i == 3
  puts i
end
Repeats printing 2 endlessly.
Ruby
for i in 1..5
  puts i
  redo if i == 2
end
Sample Program

This program shows how next skips printing 3, redo repeats printing 4, and break stops the loop at 5.

Ruby
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
OutputSuccess
Important Notes

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.

Summary

break stops the loop completely.

next skips to the next loop cycle.

redo repeats the current loop step.