Ruby: Counting occurrences of an item in an array / enumerable

Posted About 9 years ago. Visible to the public.

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
Thomas Klemm
Last edit
About 9 years ago
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Klemm to makandra dev (2015-02-20 13:57)