Enumerable#count

Returns: Integer · Updated March 13, 2026 · Enumerable
ruby enumerable

The count method returns the number of elements in a collection. When given a block, it counts only elements for which the block evaluates to true. This is one of the most frequently used methods for analyzing collections in Ruby.

Basic Usage

Count all elements in an array:

numbers = [1, 2, 3, 4, 5]
numbers.count
# => 5

This is equivalent to calling .size or .length on the array.

Counting Matching Elements

Pass a block to count only elements that satisfy a condition:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_count = numbers.count { |n| n.even? }
# => 5

The block must return a truthy value for elements you want to count.

Counting Specific Values

You can also count occurrences of a specific value without a block:

scores = [95, 82, 95, 78, 95, 92]
scores.count(95)
# => 3

This searches for exact equality using the == operator.

With Hashes

stock = { apples: 5, oranges: 3, bananas: 0, grapes: 12 }
stock.count
# => 4

# Count entries where value > 0
stock.count { |_k, v| v > 0 }
# => 3

The block receives both key and value as parameters.

Practical Examples

Survey Results Analysis

responses = ["yes", "no", "yes", "maybe", "yes", "no", "yes"]
yes_count = responses.count("yes")
# => 4

Filtering Database Records

users = [
  { name: "Alice", active: true },
  { name: "Bob", active: false },
  { name: "Carol", active: true }
]

active_users = users.count { |u| u[:active] }
# => 2

Checking Array Completeness

form_fields = ["email", "phone", "address", "name"]
filled = form_fields.count { |f| f.present? }
# varies based on actual values

Performance Note

The count method traverses the entire collection, so be mindful when working with large datasets or external data sources. For a simple size check, .size or .length is more efficient since it doesn’t require iteration.

Empty Collections

[].count
# => 0

[].count { |x| x > 5 }
# => 0

Return Value

count always returns an integer. For empty collections, it returns 0 regardless of whether a block is provided.

See Also