Ruby — Iteration with each, next, and break
Ruby each passes successive elements to a block. next advances to the next element, and break stops the traversal early.
A simple example
Print the numbers 1 to 3
- Start with Start at 1
- Do this Visit 1, 2, 3
- Result 1 → 2 → 3
(1..3).each do |n|
puts n
end
1 2 3
Stop at the end of a batch
each yields individual elements to the block. next skips to the next yield and break stops iteration. The block updates total from the surrounding scope.
A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.
Run the example
Ruby 2.7 or later. Run these commands from the directory containing the example.
ruby lesson.rb
total = 0
[4, -1, 0, 7].each do |reading|
break if reading.zero?
next if reading.negative?
total += reading
end
puts total
4
Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.
Traverse indices with for and each_index
Use for to traverse the positions from each_index. Ruby for shares its local scope with the surrounding code, while parameters of an each block are block-local.
Three supply bins contain 3, 0 and 5 items. Skip printing the empty middle bin but keep its position in the sequence. The last line must still refer to bin 3.
Run this example
Save this program as lesson.rb and run it separately.
ruby lesson.rbbins = [3, 0, 5]
for index in bins.each_index
next if bins[index].zero?
puts "bin #{index + 1}: #{bins[index]}"
end
bin 1: 3 bin 3: 5
A bin with quantity zero produces no line. The output uses one-based bin numbers while array access stays zero-based.
Try it yourself
What changes if the input is 4, −1, 7, 0?
Check your answer
Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.