String#count
str.count([other_str]+) -> integer 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
The parameter table above shows the method’s single argument type: one or more strings representing character sets. The method treats each string as a set of characters, counting how many times any character from those sets appears in the receiver. When you pass multiple strings, the method intersects the sets before counting.
hello = "hello world"
hello.count("l")
# => 3
hello.count("o")
# => 2
Each call to count with a single argument tallies how many times any character in that argument string appears in the receiver. The argument is a set of characters, not a substring — "hello".count("he") counts h and e individually, not the sequence he.
Counting multiple character sets
text = "hello HELLO"
text.count("A-Za-z")
# => 10
The range syntax A-Z and a-z uses ASCII ordering, so "A-Za-z" covers all uppercase and lowercase English letters without listing them individually. This is much more concise than typing out the full alphabet as an argument.
When you pass multiple strings, the method finds the intersection of all character sets and counts only those characters.
"hello".count("hl", "l")
# => 2
"hello".count("lo", "el")
# => 2
The intersection rule is the part of count that surprises newcomers. In "hello".count("lo", "el"), the first set is {l, o} and the second is {e, l}. The intersection is {l}, so only the two l characters in “hello” are counted — explaining the result of 2. When the sets have no overlap, count returns 0 regardless of the string content. This intersection behavior makes count especially useful for checking characters that satisfy multiple criteria simultaneously, like “all lowercase vowels” or “letters that are also in a specific set.” The ability to intersect character sets in a single call avoids writing a custom loop with multiple conditions.
Practical use case
def count_vowels(str)
str.count("aeiouAEIOU")
end
count_vowels("hello world")
# => 3
The vowel-counting example shows count at its simplest: pass the set of characters you care about, and the method returns the total number of matches. This is often enough for quick text checks where you only need a count, not the positions or identities of the matching characters.
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}
The character_frequency method calls count once per unique character, which is fine for strings with a small character set but does a full scan for each distinct character. For large texts with many unique characters, a single-pass tally with each_char and a counting hash would be more efficient. Use this pattern when the character set is known to be small.
Input validation
def contains_only_digits?(str)
str.count("0-9") == str.length
end
contains_only_digits?("12345") # => true
contains_only_digits?("12a45") # => false
The digits-only check uses count to compare the number of digit characters against the total string length. If they match, every character is a digit. This is a cleaner one-liner than iterating with all?, but it only works for simple character-class checks — more complex validation (like checking for a specific format) needs a regex or a more detailed parse.
Whitespace handling
sentence = "hello world"
sentence.count(" ") # => 5
sentence.count("\s") # => 5 (includes tabs, newlines)
Note that "\s" in the count argument is a literal backslash and s, not a regex shorthand for whitespace. The method does not interpret backslash escapes as character classes — \s means the two characters \ and s literally. To count actual whitespace, pass space, tab, and newline characters directly or use a different approach.
Errors
No special errors are raised. If an empty string is passed, the method returns 0.
"hello".count("")
# => 0
Passing an empty string as the character set always returns 0 — there is nothing to count. This is consistent with the intersection rule: an empty set intersected with any other set is empty, so no characters match.
Counting characters with a narrow rule
count is useful when the job is just to measure how many characters from a small set appear in the string. That keeps the code direct and skips the need for a longer loop when a single method call can state the answer. It works especially well for quick validation, frequency checks, and simple text analysis where the question is narrow and the input is already in hand. When the rule gets more complex, a different approach may give the reader more context.
The method is also handy when the goal is to compare text samples without pulling in heavier parsing logic. A quick count can tell you whether a field looks empty, whether a string is mostly digits, or whether a specific character keeps showing up more than expected. Those checks are small, but they are often enough to guide the next branch of code. In that role, count keeps the rule visible and the decision easy to explain.
The result can also be a quick sanity check before the code does something more expensive. If the count looks wrong, the caller can stop early and avoid a larger parse or a more detailed match. That makes count useful not just for measuring text, but for deciding whether the text is worth processing further at all. The call stays short, and the reason for using it stays plain.