Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#count

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

Returns a count of specified elements.

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

Example
[0, :one, 'two', 3, 3.0].count # => 5

With argument object given, returns the count of elements == to object:

Example
[0, :one, 'two', 3, 3.0].count(3) # => 2

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 object and a block given, issues a warning, ignores the block, and returns the count of elements == to object.

Related: see Methods for Querying.

See also #concat #cycle #compact! #delete also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0