Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say you have this array:

arr = w|one two three|

How can I iterate over it by having two consecutive elements as block arguments like this:

1st cycle: |nil, 'one'|
2nd cycle: |'one', 'two'|
3rd cycle: |'two', 'three'|

Sofar I came only with this:

arr.each_index { |i| [i - 1 < 0 ? nil: arr[i - 1], arr[i]] }

Any better solutions? Is there something like each(n)?

like image 888
Alexander Popov Avatar asked Dec 11 '22 02:12

Alexander Popov


1 Answers

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)

like image 187
Marek Lipka Avatar answered Jan 05 '23 01:01

Marek Lipka