Read more

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

Thomas Klemm
February 20, 2015Software engineer

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
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Posted by Thomas Klemm to makandra dev (2015-02-20 14:57)