ng khanh ng khanh - 5 months ago 14
Ruby Question

Ruby group every 4 elements

i have array

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


i want to get same-size array with elements grouped from source array and select-able size 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 result array doesn't have last three
[[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]]

Note: I am using ruby 2.0

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]
Comments