Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Enumerable#count

() -> ::Integer
(E) -> ::Integer
() { (E) -> ::boolish } -> ::Integer
count → integer
count(object) → integer
count {|element| ... } → integer

Returns the count of elements, based on an argument or block criterion, if given.

With no argument and no block given, returns the number of elements:

Example
[0, 1, 2].count                # => 3
{foo: 0, bar: 1, baz: 2}.count # => 3

With argument object given, returns the number of elements that are == to object:

Example
[0, 1, 2, 1].count(1)           # => 2

With a block given, calls the block with each element and returns the number of elements for which the block returns a truthy value:

Example
[0, 1, 2, 3].count {|element| element < 2}              # => 2
{foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
See also #compact #cycle #collect_concat #detect also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0