Ruby Array Access 2 Consecutive(Chained) Elements At a Time

Ruby array access 2 consecutive(chained) elements at a time

Ruby reads your mind. You want cons ecutive elements?

[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

Iterate over loop accessing two elements if they exist

You can use each_cons:

array.each_cons(2) do |a, b|
process(a, b)

How to iterate over an array in overlapping groups of n elements?

You can add nil as the first element of your arr and use Enumerable#each_cons method:

arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]

(I'm using map here to show what exactly is returned on each iteration)

Iterate pairwise through a ruby array

You are looking for each_cons:

(1..6).each_cons(2) { |a, b| p a: a, b: b }
# {:a=>1, :b=>2}
# {:a=>2, :b=>3}
# {:a=>3, :b=>4}
# {:a=>4, :b=>5}
# {:a=>5, :b=>6}

How can I slice array values?

#=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]

Iterate over a array and returning the next and the element before current

Take look at Enumerable#each_cons method:

[nil, *array, nil].each_cons(3){|prev, curr, nxt|
puts "prev: #{prev} curr: #{curr} next: #{nxt}"

prev: curr: a next: b
prev: a curr: b next: c
prev: b curr: c next:

If you like, you can wrap it in new Array method:

class Array
def each_with_prev_next &block
[nil, *self, nil].each_cons(3, &block)
#=> nil

array.each_with_prev_next do |prev, curr, nxt|
puts "prev: #{prev} curr: #{curr} next: #{nxt}"

Overlapping equivalent of Array#slice

each_cons (docs) does this. You just pass it the size of the chunks you want and it will yield them to the block you pass.

If you actually want the arrays, then you can of course chain this with to_a, for example


Ruby Iteration - Trying to match two numbers in a single pass

Don't use


To get a series of paired objects.

Use each_cons as suggested by steenslag or glenn mcdonald.

Enumerating over an array but passing a subset of the array to the block instead of a single element

each_cons(3) behaves like that. It is in Enumerable (Array includes Enumerable), that's why you couldn't find it.

Related Topics

Leave a reply