Loop control with break next and redo
suggest changeThe flow of execution of a Ruby block may be controlled with the break, next, and redo statements.
break
The break statement will exit the block immediately. Any remaining instructions in the block will be skipped, and the iteration will end:
actions = %w(run jump swim exit macarena)
index = 0
while index < actions.length
action = actions[index]
break if action == "exit"
index += 1
puts "Currently doing this action: #{action}"
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
next
The next statement will return to the top of the block immediately, and proceed with the next iteration. Any remaining instructions in the block will be skipped:
actions = %w(run jump swim rest macarena)
index = 0
while index < actions.length
action = actions[index]
index += 1
next if action == "rest"
puts "Currently doing this action: #{action}"
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
# Currently doing this action: macarena
redo
The redo statement will return to the top of the block immediately, and retry the same iteration. Any remaining instructions in the block will be skipped:
actions = %w(run jump swim sleep macarena)
index = 0
repeat_count = 0
while index < actions.length
action = actions[index]
puts "Currently doing this action: #{action}"
if action == "sleep"
repeat_count += 1
redo if repeat_count < 3
end
index += 1
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
# Currently doing this action: sleep
# Currently doing this action: sleep
# Currently doing this action: sleep
# Currently doing this action: macarena
Enumerable iteration
In addition to loops, these statements work with Enumerable iteration methods, such as each and map:
[1, 2, 3].each do |item|
next if item.even?
puts "Item: #{item}"
end
# Item: 1
# Item: 3
Block result values
In both the break and next statements, a value may be provided, and will be used as a block result value:
even_value = for value in [1, 2, 3]
break value if value.even?
end
puts "The first even value is: #{even_value}"
# The first even value is: 2