Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Range#count
count → integer
count(object) → integer
count {|element| ... } → integer
range.c
View on GitHub ↗
static VALUE
range_count(int argc, VALUE *argv, VALUE range)
{
if (argc != 0) {
/* It is odd for instance (1...).count(0) to return Infinity. Just let
* it loop. */
return rb_call_super(argc, argv);
}
else if (rb_block_given_p()) {
/* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
* Infinity. Just let it loop. */
return rb_call_super(argc, argv);
}
VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
if (NIL_P(beg) || NIL_P(end)) {
/* We are confident that the answer is Infinity. */
return DBL2NUM(HUGE_VAL);
}
if (is_integer_p(beg)) {
VALUE size = range_size(range);
if (!NIL_P(size)) {
return size;
}
}
return rb_call_super(argc, argv);
}
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
(1..4).count # => 4 (1...4).count # => 3 ('a'..'d').count # => 4 ('a'...'d').count # => 3 (1..).count # => Infinity (..4).count # => Infinity
With argument object, returns the number of object found in self, which will usually be zero or one:
Example
(1..4).count(2) # => 1 (1..4).count(5) # => 0 (1..4).count('a') # => 0
With a block given, calls the block with each element; returns the number of elements for which the block returns a truthy value:
Example
(1..4).count {|element| element < 3 } # => 2
Related: Range#size.