ironsand ironsand - 6 months ago 7
Ruby Question

How to count a multiple values in an array

I can count a number of a value by

Array#count
.

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


And how can I count a number of 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 this code is a bit redundant, how would you write the function like this?

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