DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get Every Nth Member Of A Ruby Array

05.28.2005
| 8315 views |
  • submit to reddit
        
class Array
  def every(n)
    select {|x| index(x) % n == 0}
  end
  def every_other
    every 2
  end
end

Now you can do things like:
[1, 2, 3, 4].every_other
=> [1, 3]

["fish", "hesitantly", "shampoo", "terminal", "sharp", "yarn", "golfer"].every 3
=> ["fish", "terminal", "golfer"]