Method: Enumerable#count
- Defined in:
- enum.c
#count ⇒ Integer #count(object) ⇒ Integer #count {|element| ... } ⇒ Integer
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:
[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:
[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:
[0, 1, 2, 3].count {|element| element < 2} # => 2
{foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'enum.c', line 297
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);
}
|