Reputation: 51
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?
Upvotes: 4
Views: 92
Reputation: 11183
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]]
Upvotes: 1