Patrick Duvall
Patrick Duvall

Reputation: 51

Simple ruby array splitting

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

Answers (2)

iGian
iGian

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

Tyl
Tyl

Reputation: 5252

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

Check doc for each_cons.

Upvotes: 6

Related Questions