Count
This Ruby method counts characters, not substrings. It receives a string
containing a set of characters. It returns the total number of those characters it finds.
Count()
does not support regular expression metacharacters like "\w" but it supports some ranges. We can specify all letters (upper and lower) and all digits.
To begin we use the count method several times on a string
containing the text "Plutarch." We count the letter "a," which occurs only once.
value = "Plutarch" # The letter "a" occurs once. a = value.count "a" puts a # The letters "a" and "r" occur twice in total. b = value.count "ar" puts b # Letters in range "a" through "c" occur twice in total. c = value.count "a-c" puts c1 2 2
Here are more examples for ranges. We invoke count()
twice here to count all letters (lower and upper) and all digits (0 through 9).
string
"0-9," which covers all possible digits.# Part 1: count all ASCII lowercase and uppercase letters. value = "Bird?!" result1 = value.count("a-zA-Z") puts result1 # Part 2: count all digits. value2 = "cat57" result2 = value2.count("0-9") puts result24 2
We cannot pass a regexp
metacharacter to the count method. It will not match "word" characters with the metacharacter "\w" and instead counts the letters directly.
value = "word" # We cannot use this metacharacter to mean "word characters." # ... It matches "w" so returns 1, not 4. puts value.count("\w")1
We invoked the count method on strings to count certain letters and ranges of letters and digits. This method can replace some loops (or iterator calls to each_char
).