I would like to split my array in the following way:
current_arr = [1,2,3,4,5]
new_arr = [[1,2,3], [2,3,4], [3,4,5]]
#each_slice
and #combination
are close to what I want but not quite.
How could I split my array as in the example?
[1,2,3,4,5].each_cons(3).to_a
#=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Check doc for each_cons.
Just for fun:
ary = [1,2,3,4,5]
n = 3
(ary.size - n + 1).times.each_with_object([]) { |_, a| a << ary.first(n); ary.rotate! }
#=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With