Ruby — Skipping iterations with next
Ruby next ends the current iteration of a block and lets each yield its next element. A guard clause keeps the normal calculation at one indentation level.
A simple example
Skip just the number 2
- Start with Visit 1 through 3
- Do this Skip 2
- Result 1 → 3
(1..3).each do |n|
next if n == 2
puts n
end
1 3
Exclude invalid readings while keeping zero
Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. negative? excludes invalid readings directly. A zero measurement still goes through both updates and can affect a later average.
A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.
Run the example
Use Ruby 2.6 or later. Run these commands from the directory containing the example.
ruby lesson.rb
count = 0
sum = 0
[-2, 0, 4, -1, 6].each do |reading|
next if reading.negative?
count += 1
sum += reading
end
puts "#{count} readings, sum #{sum}"
3 readings, sum 10
The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.
Try it yourself
Append −3 and then 0. What should the count and sum become?
Check your answer
The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.