Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements in array of arrays

Tags:

ruby

element = [["BLUE", "CAT", "BEAR"], ["BALL", "CHAIR", "BOW"], ["CLOWN", "COLA", "PARROT", "LOVE"]]

There are obviously ten elements across the arrays. How do I find the count without flattening the array?

like image 247
olafsadventures Avatar asked Feb 04 '26 00:02

olafsadventures


2 Answers

With Ruby 2.4,

element.sum(&:size) #=> 10
like image 177
Cary Swoveland Avatar answered Feb 06 '26 00:02

Cary Swoveland


ary = [["BLUE", "CAT", "BEAR"], ["BALL", "CHAIR", "BOW"], ["CLOWN", "COLA", "PARROT", "LOVE"]]

sum = ary.inject(0) { |tot, e| tot + e.size }

 => 10
like image 33
seph Avatar answered Feb 06 '26 00:02

seph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!