Lesson contents

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

  1. Start with Start at 1
  2. Do this Visit 1, 2, 3
  3. Result 1 → 2 → 3
Each pass prints one number on its own line. After 3 the loop has no more values to visit.
lesson.rb
(1..3).each do |n|
  puts n
end
Output
1
2
3
Advertisements

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.

Readings: 4, −1, 0, 7. End marker: 0. This batch totals: 4.
Find the end of a scanner batch

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
lesson.rb
total = 0
[4, -1, 0, 7].each do |reading|
  break if reading.zero?
  next if reading.negative?
  total += reading
end
puts total
Output
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.

Bin 1: 3 items. Bin 2: Empty. Bin 3: 5 items.
Keep the printed bin numbers

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.rb
lesson.rb
bins = [3, 0, 5]
for index in bins.each_index
  next if bins[index].zero?
  puts "bin #{index + 1}: #{bins[index]}"
end
Output
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.

Ruby language documentation

Related tags

  • Ruby
  • iteration
  • loop control
  • accumulators