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
array.c
View on GitHub ↗
static VALUE
rb_ary_count(int argc, VALUE *argv, VALUE ary)
{
long i, n = 0;
if (rb_check_arity(argc, 0, 1) == 0) {
VALUE v;
if (!rb_block_given_p())
return LONG2NUM(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
v = RARRAY_AREF(ary, i);
if (RTEST(rb_yield(v))) n++;
}
}
else {
VALUE obj = argv[0];
if (rb_block_given_p()) {
rb_warn("given block not used");
}
for (i = 0; i < RARRAY_LEN(ary); i++) {
if (rb_equal(RARRAY_AREF(ary, i), obj)) n++;
}
}
return LONG2NUM(n);
}
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.