Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple ruby array splitting

Tags:

ruby

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?

like image 899
Patrick Duvall Avatar asked Mar 04 '23 17:03

Patrick Duvall


2 Answers

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

Check doc for each_cons.

like image 73
Tiw Avatar answered Mar 08 '23 06:03

Tiw


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]]
like image 41
iGian Avatar answered Mar 08 '23 04:03

iGian