break and next
Prerequisites: Iterators
Two keywords change how a loop runs:
breakstops the loop completely.nextskips the rest of the current pass and moves on to the next one.
Example
(1..10).each do |n|
next if n.even?
break if n > 7
puts n
end
Expected output
1
3
5
7
Even numbers are skipped by next. When n reaches 9 (the first odd
number over 7), break ends the loop.
Asking until the input is valid
loop do ... end with break is the standard pattern for repeating
until the user gets it right:
loop do
print "Enter a number between 1 and 10: "
input = gets.to_s.chomp
number = Integer(input, exception: false)
if number && (1..10).cover?(number)
puts "Thanks, you picked #{number}"
break
end
puts "That's not valid — try again."
end
Enter a number between 1 and 10: twelve
That's not valid — try again.
Enter a number between 1 and 10: 4
Thanks, you picked 4
Common mistakes
- Using
returninstead ofbreakto leave a loop at the top level of a script —returnexits the whole method (or the whole script), not just the loop.
Practice
Print the numbers from 1 to 20, skipping every multiple of 3, and stop completely when you reach 16.
Show solution
(1..20).each do |n|
break if n == 16
next if (n % 3).zero?
puts n
end