ironsand ironsand - 6 months ago 9
Ruby Question

How to count multiple values in an array

I can count a value using

Array#count
.

numbers = [1, 2, 5, 5, 1, 3, 1, 2, 4, 3]
numbers.count(1) #=> 3


How can I count multiple values in an array?

What I wrote were:

numbers.count(1) + numbers.count(2) #=> 5
[1,2].map{|i| numbers.count(i)}.sum #=> 5


I think these are a bit redundant.

Answer

count can also take a block, so you can write this in a way that only traverses the array once:

numbers.count {|i| [1,2].include? i } # => 5

Or for fun, in a slightly more functional/point-free style:

numbers.count &[1,2].method(:include?) # => 5