Method count
returns an integer count of the number of items in a collection that match a given criterion.
The method is available as:
- Array#count.
- Range#count.
- String#count (with a special implementation that is not discussed here).
- Enumerable#count, which is included or extended in a number of classes in the Ruby core and standard library.
There are three ways to call the method:
- With no argument and no block, returns the count of items in the collection:
[0, 1, 2].count # => 3
[].count # => 0
- With argument
object
, returns the count of items== object
in the collection:
[0, 1, 2, 0.0].count(0) # => 2
[0, 1, 2].count(3) # => 0
- With a block, calls the block with each item in the collection; returns the count of elements for which the block returns a truthy value:
[0, 1, 2, 3].count {|element| element > 1} # => 2
More methods at #rubymethodoftheday.