How to iterate over an array in overlapping groups of n elements?
Let's say you have this array:
arr = w|one two three|
How can I iterate over it having two consecutive elements as block arguments like this:
1st cycle: |nil, 'one'|
2nd cycle: |'one', 'two'|
3rd cycle: |'two', 'three'|
Zophar I only came with this:
arr.each_index { |i| [i - 1 < 0 ? nil: arr[i - 1], arr[i]] }
Any better solutions? Is there something like each(n)
?
+3
source to share
2 answers
You can add nil
as the first element of yours arr
and use the method Enumerable#each_cons
:
arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]
(I am using map
here to show what exactly is returned on each iteration)
+8
source to share