Never been to DZone Snippets before?

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

Get every nth member of a Ruby array (See related posts)

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"]

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts