Over a million developers have joined DZone.

Advanced Iterating In Ruby With 'enumerator'

DZone's Guide to

Advanced Iterating In Ruby With 'enumerator'

Free Resource
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]

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}