Read more

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

Henning Koch
January 07, 2011Software engineer at makandra GmbH

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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]
Posted by Henning Koch to makandra dev (2011-01-07 11:14)