Iterate over every n-th element of a Range in Ruby

If you want to iterate over a Range Show archive.org snapshot , but only look at every n-th element, use the step Show archive.org snapshot method:

(0..10).step(5).each do |i|
  puts i
end

# Prints three lines:
# 0
# 5
# 10

This is useful e.g. to iterate over every Monday in a range of Dates.

If you are using Rails or ActiveSupport, calling step without a block will return an array of matching elements:

(0..10).step(5) 
# => [0, 5, 10]
Henning Koch