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

Posted . Visible to the public.

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
Keywords
cweek, weekday
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-01-07 10:14)