Sum of array in groups excluding potential nil items

I have an array like this:

[1,2,3,4,5,nil,7,8,9,nil,nil,12]

How can i get an array of the sums of these numbers in groups of 4, so that when a nil is encountered, it’s treated as zero ?

So that the outcome would be:

[10, 20, 21]

>Solution :

Something like this should work (probably there are more efficient solutions):

>> [1, 2, 3, 4, 5, nil, 7, 8, 9, nil, nil, 12].each_slice(4).map { |slice| slice.sum(&:to_i) }
=> [10, 20, 21]

Leave a Reply