Ruby — Break from an each block
Ruby break can end iteration performed by each. A guard using break if exits as soon as the loop encounters an unaffordable job.
A simple example
Stop before printing 3
- Start with Visit 1 through 4
- Do this Leave at 3
- Result 1 → 2
(1..4).each do |n|
break if n == 3
puts n
end
1 2
Stop before the first unaffordable job
Process the queue in order with a budget of 10. Stop the loop as soon as the next job would exceed the remaining budget. The guard leaves the job and every later item unprocessed. The accepted count and remaining balance are locals initialized outside the block.
A print queue has ten credits and must serve jobs in arrival order. Jobs costing four and three leave three credits. The next job costs eight, so the queue stops before the smaller job behind it.
Run the example
Use Ruby 2.6 or later. Run these commands from the directory containing the example.
ruby lesson.rb
remaining = 10
accepted = 0
[4, 3, 8, 1].each do |cost|
break if cost > remaining
remaining -= cost
accepted += 1
end
puts "#{accepted} accepted, #{remaining} left"
2 accepted, 3 left
The first two jobs cost 4 and 3, leaving 3. The next costs 8, so processing stops before the later job costing 1.
Try it yourself
Replace the cost of 8 with 3. What changes?
Check your answer
The third job exactly fits. Three jobs are accepted and the remaining budget is zero. The last job cannot run.