Ruby: Counting occurrences of an item in an array / enumerable
Enumerable#count
Show archive.org snapshot
can do three things.
- With no argument provided, it returns the number of items.
- With an argument, it returns the number of items matching the given value.
- With a block, it counts the number of elements yielding a truthy value.
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count { |x| x % 2 == 0 } #=> 3