Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading