Home
Map
String count UseCall the count method to count characters and ranges of characters in a string.
Ruby
This page was last reviewed on Feb 2, 2024.
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.
Syntax notes. 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.
Regexp Match
String index
First example. 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.
Then We count the letters "a" and "r," and finally we count a range of 3 letters.
Tip We can use a range of characters within the argument to count: "a-c" means "abc."
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 c
1 2 2
Letter, digit ranges. Here are more examples for ranges. We invoke count() twice here to count all letters (lower and upper) and all digits (0 through 9).
Part 1 We can count all lowercase and all uppercase letters—this results in the total letter count.
Part 2 We can count all digits by using the 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 result2
4 2
Metacharacter issue. 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
A review. 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).
String each char
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 2, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.