Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#count

array.count → an_integer
array.count(obj) → an_integer
array.count {|element| ... } → an_integer

Returns a count of specified elements.

With no argument and no block, returns the count of all elements:

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

With argument obj, returns the count of elements eql? to obj:

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

With no argument and a block given, calls the block with each element; returns the count of elements for which the block returns a truthy value:

Example
[0, 1, 2, 3].count {|element| element > 1} # => 2

With argument obj and a block given, issues a warning, ignores the block, and returns the count of elements eql? to obj:

See also #concat #cycle #compact! #deconstruct also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1