ng khanh ng khanh - 5 months ago 32
Ruby Question

Group every n elements

I have an array:

a = [1,2,3,4,5,6]


I want an array of arrays taking the elements up to a certain amount like:

b = group(a,4) = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6],[5,6],[6]]


I tried:

a.each_cons(4) {|x1,x2,x3,x4| b[a.index(x1) = [x1,x2,x3,x4]}


but the resulting array doesn't have the last three elements:

[[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]]

Answer
a = [1,2,3,4,5,6]
a.map.with_index { |e, i| a.slice(i, 4) }
#⇒ [1, 2, 3, 4]
#⇒ [2, 3, 4, 5]
#⇒ [3, 4, 5, 6]
#⇒ [4, 5, 6]
#⇒ [5, 6]
#⇒ [6]