0
0
RubyHow-ToBeginner · 3 min read

How to Use Count in Ruby: Syntax and Examples

In Ruby, the count method returns the number of elements in an array, string, or enumerable that meet a condition or match a value. You can use it without arguments to count all elements, with an argument to count matching elements, or with a block to count elements for which the block returns true.
📐

Syntax

The count method can be used in three main ways:

  • collection.count - counts all elements.
  • collection.count(item) - counts elements equal to item.
  • collection.count { |element| condition } - counts elements where the block condition is true.
ruby
array = [1, 2, 3, 2, 4]

# Count all elements
array.count

# Count elements equal to 2
array.count(2)

# Count elements greater than 2
array.count { |x| x > 2 }
💻

Example

This example shows how to use count to count total elements, specific values, and elements matching a condition in an array.

ruby
numbers = [5, 3, 7, 3, 9, 3]

puts "Total elements: #{numbers.count}"
puts "Count of 3: #{numbers.count(3)}"
puts "Count of numbers greater than 5: #{numbers.count { |n| n > 5 }}"
Output
Total elements: 6 Count of 3: 3 Count of numbers greater than 5: 2
⚠️

Common Pitfalls

One common mistake is mixing the argument and block forms. If you provide both an argument and a block, Ruby ignores the block. Also, using count on a string counts characters, not words.

ruby
words = "hello world"

# Counts characters, not words
puts words.length

# Wrong: both argument and block (block ignored)
arr = [1, 2, 3, 2]
puts arr.count(2) { |x| x > 1 }  # block ignored, counts 2s only

# Correct: use either argument or block
puts arr.count { |x| x > 1 }
Output
11 2 3
📊

Quick Reference

UsageDescriptionExample
countCounts all elements[1,2,3].count #=> 3
count(item)Counts elements equal to item[1,2,2].count(2) #=> 2
count { |e| condition }Counts elements matching condition[1,2,3].count { |x| x > 1 } #=> 2

Key Takeaways

Use count without arguments to get total elements in a collection.
Pass an argument to count to count elements equal to that value.
Use a block with count to count elements matching a condition.
Do not use both argument and block together; the block will be ignored.
On strings, count returns the number of characters, not words.