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
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, 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: