count(...)
public
Returns the number of elements. If an argument is given, counts the number
of elements which equals to obj. If a block is given, counts the
number of elements yielding a true value.
ary = [1, 2, 4, 2]
ary.count
ary.count(2)
ary.count{|x|x%2==0}
Show source
/*
* call-seq:
* array.count -> int
* array.count(obj) -> int
* array.count { |item| block } -> int
*
* Returns the number of elements. If an argument is given, counts
* the number of elements which equals to <i>obj</i>. If a block is
* given, counts the number of elements yielding a true value.
*
* ary = [1, 2, 4, 2]
* ary.count
* ary.count(2)
* ary.count{|x|x%2==0}
*
*/
static VALUE
rb_ary_count(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
long n = 0;
if (argc == 0) {
VALUE *p, *pend;
if (!rb_block_given_p())
return LONG2NUM(RARRAY_LEN(ary));
for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
if (RTEST(rb_yield(*p))) n++;
}
}
else {
VALUE obj, *p, *pend;
rb_scan_args(argc, argv, "1", &obj);
if (rb_block_given_p()) {
rb_warn("given block not used");
}
for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
if (rb_equal(*p, obj)) n++;
}
}
return LONG2NUM(n);
}