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

Advanced Iterating In Ruby With 'enumerator'

04.15.2005
| 9106 views |
  • submit to reddit
        require 'enumerator'

ary = [ 1, 2, 3, 4 ]

# iterate over two elements at a time
ary.each_slice(2) { |a,b| p [a, b] }

# iterate over every pair of consecutive pair of numbers
ary.each_cons(2) { |a, b| p [a, b] }

# An Enumerable::Enumerator object can be created as well,
# that mixes in Enumerable, for further processing:
ary.enum_for(:each_cons, 2).map { |a,b| a + b  } # => [3, 5, 7]