Home > Net >  Sum of array in groups excluding potential nil items
Sum of array in groups excluding potential nil items

Time:11-24

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]

CodePudding user response:

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

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

array.each_slice(4).map { |slice| slice.sum(&:to_i) }
#=> [10, 20, 21]

CodePudding user response:

If you prefer working with indices directly, you could:

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

(0...a.size).step(4).map { |i| a[i...i 4].compact.sum }
# => [10, 20, 21]
  • Related