Enumerable#count
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.
Enumerable#count is a practical method because it covers three related questions with one API: how many items are there, how many match a value, and how many satisfy a custom condition. That makes it easy to read in reporting code, validation code, and quick data checks.
Basic usage
Count all elements in an array:
This is the simplest form of count, and it is often the one people reach for first. It tells you the size of the collection without needing a separate call to size or length.
numbers = [1, 2, 3, 4, 5]
numbers.count
# => 5
This is equivalent to calling .size or .length on the array. Both alternatives return the same number, so the choice between them is mostly about consistency with the rest of the codebase. The advantage of count is that it works identically across all Enumerable types, while .size and .length may behave differently on lazy enumerators or custom collections.
counting matching elements
Pass a block to count only elements that satisfy a condition:
The block form is useful when the answer depends on something more specific than raw equality. You can count even numbers, non-empty strings, or any other subset that you can describe in Ruby code.
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.
That rule makes the method flexible and predictable. As long as the block returns something truthy, the item is included in the total.
counting specific values
You can also count occurrences of a specific value without a block:
This version is handy when you are looking for repeated entries, such as survey answers or duplicate values in a list.
scores = [95, 82, 95, 78, 95, 92]
scores.count(95)
# => 3
This searches for exact equality using the == operator. The value form is simpler than the block form because it only checks whether each element is the same object, not whether it satisfies a custom predicate. When you know the exact value you are tracking, the argument form saves a few keystrokes and reads more directly.
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.
That gives you enough information to count keys, values, or combinations of both. In practice, it makes count fit naturally into small hash-processing tasks.
This flexibility is what makes count useful in everyday Ruby code. You can keep the expression short while still making the counting rule obvious to the reader.
practical examples
The examples below show count in a few common situations. Each one highlights a slightly different way the method can answer “how many?” without forcing you to build a custom loop. The same method can read as a size check, a filter count, or a value counter, depending on the arguments you pass.
survey results analysis
responses = ["yes", "no", "yes", "maybe", "yes", "no", "yes"]
yes_count = responses.count("yes")
# => 4
filtering database records
Counting active users or matching records is a natural fit for count with a block because the condition lives right next to the data it filters. The alternative — selecting with select and then calling size — allocates an intermediate array, while count tallies without building a new collection. For database-style record lists where the number of matching entries matters more than the entries themselves, count gives you the answer in one pass.
users = [
{ name: "Alice", active: true },
{ name: "Bob", active: false },
{ name: "Carol", active: true }
]
active_users = users.count { |u| u[:active] }
# => 2
checking array completeness
When you need to verify that every expected field has a value, count with a block reads more naturally than a manual loop with a counter variable. It keeps the check declarative: you describe what counts as filled and let the method tally the result. That pattern works equally well for form validation, data import checks, and any situation where the goal is to confirm that a list is fully populated before proceeding.
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.
That performance difference matters most when the collection already knows its size. If you only need the total number of elements, use the cheaper method first; if you need to evaluate a condition, count is the right tool.
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
Array#size— returns collection size (more efficient for just counting all)Enumerable#any?— checks if any element matchesEnumerable#all?— checks if all elements matchEnumerable#select— returns matching elements