Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#count

count(*selectors) → integer

Returns the total number of characters in self that are specified by the given selectors (see Multiple Character Selectors):

Example
a = "hello world"
a.count "lo"                   #=> 5
a.count "lo", "o"              #=> 2
a.count "hello", "^l"          #=> 4
a.count "ej-m"                 #=> 4

"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo"   #=> 4

c = "hello world\\r\\n"
c.count "\\"                   #=> 2
c.count "\\A"                  #=> 0
c.count "X-\\w"                #=> 3
See also #concat #crypt #codepoints #dedup also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0