Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns a count of specified elements.
With no argument and no block, returns the count of all elements:
[0, 1, 2].count # => 3
[].count # => 0
With argument obj, returns the count of elements == to obj:
[0, 1, 2, 0.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:
[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 == to obj:
 
               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);
}
            

Was this page useful?