Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Range#count

() -> (::Integer | ::Float)
(untyped) -> ::Integer
() { (E) -> ::boolish } -> ::Integer
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:

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.

See also #clamp #cover? #bsearch #each also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0