End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#count
count → integer
count(object) → integer
count {|element| ... } → integer
enum.c
View on GitHub ↗
static VALUE
enum_count(int argc, VALUE *argv, VALUE obj)
{
VALUE item = Qnil;
struct MEMO *memo;
rb_block_call_func *func;
if (argc == 0) {
if (rb_block_given_p()) {
func = count_iter_i;
}
else {
func = count_all_i;
}
}
else {
rb_scan_args(argc, argv, "1", &item);
if (rb_block_given_p()) {
rb_warn("given block not used");
}
func = count_i;
}
memo = MEMO_NEW(item, 0, 0);
rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
return imemo_count_value(memo);
}
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