๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Break and Next

Break and next are words that change how a loop runs. Break stops a loop at once, and next skips one turn of a loop.

Break stops the count at 5

The loop could count to 10. The break line ends the loop when the count reaches 6.

count = 1
while count <= 10
  break if count == 6
  puts count
  count += 1
end

Next skips the number 3

The count still moves past 3. The next line skips the print step for that one turn.

count = 0
while count < 5
  count += 1
  next if count == 3
  puts count
end

Code after a break still runs

The break line ends this loop at the count of 4. The last line sits after the loop and still prints.

count = 1
while count <= 10
  break if count == 4
  puts count
  count += 1
end
puts "Stopped"

Example

count = 0
while count < 10
  count += 1
  next if count == 3
  break if count == 6
  puts count
end
puts "Done"

Key points

  • Use break to leave a loop at once.
  • Use next to skip the rest of one turn and start the next turn.
  • An if test often guards break and next so each word acts on one value only.
  • Code after a loop still runs once break leaves the loop.

In this example, the count climbs by one on each turn. The turn for 3 hits the next line, so 3 never prints. The turns for 4 and 5 print in the normal way. The count then reaches 6 and the break line ends the loop. The last line prints Done after the loop.

Note

Break leaves the whole loop, and next leaves only the current turn.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What does next do inside a loop?