String#count
str.count([other_str]+) -> integer Returns:
Integer · Updated March 13, 2026 · String Methods strings counting characters
The count method counts how many times each character in the given sets appears in the string. It’s useful for quickly tallying character frequencies without writing explicit loops.
Syntax
str.count([other_str]+)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
other_str | String | — | One or more character sets to count. Each character in these strings increments the counter. |
Examples
Basic character counting
hello = "hello world"
hello.count("l")
# => 3
hello.count("o")
# => 2
Counting multiple character sets
text = "hello HELLO"
text.count("A-Za-z")
# => 10
When you pass multiple strings, count finds the intersection of all character sets and counts only those characters.
"hello".count("hl", "l")
# => 2
"hello".count("lo", "el")
# => 2
Practical use case
def count_vowels(str)
str.count("aeiouAEIOU")
end
count_vowels("hello world")
# => 3
Common Patterns
Character frequency analysis
def character_frequency(str)
str.chars.uniq.each_with_object({}) do |char, freq|
freq[char] = str.count(char)
end
end
character_frequency("banana")
# => {"b"=>1, "a"=>3, "n"=>2}
Input validation
def contains_only_digits?(str)
str.count("0-9") == str.length
end
contains_only_digits?("12345") # => true
contains_only_digits?("12a45") # => false
Whitespace handling
sentence = "hello world"
sentence.count(" ") # => 5
sentence.count("\s") # => 5 (includes tabs, newlines)
Errors
No special errors are raised. If an empty string is passed, the method returns 0.
"hello".count("")
# => 0