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
Advanced Iterating In Ruby With 'enumerator'
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]





