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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot
Posted by Thomas Klemm to makandra dev (2015-02-20 14:57)