Home
Ruby
Word Count
This page was last reviewed on Nov 18, 2023.
Dot Net Perls
Word count. Consider a Ruby string that contains multiple words. Each word is separated by non-word characters—this means each word can be matched with the pattern "\s+."
To implement a word count method, we can split words apart and then return the resulting array's length. We can split the string with a regular expression argument.
Regexp Match
Example. The wordcount method receives a string and returns the length of an array. The split method splits words apart, treating each sequence of whitespace characters as a delimiter.
Step 1 We specify the string in which we want to count words. We consider 4 strings in total.
Step 2 Insider wordcount, we use the required regular expression, and call split(). We return the length of matches.
Important The whitespace-only string and the empty string should both contain zero words. The result is as expected.
def wordcount(value) # Step 2: split string based on one or more whitespace characters. # ... Then return the length of the array. value.split(/\s+/).length end # Step 1: specify the string. value = "To be or not to be, that is the question." puts wordcount(value) value = "Stately, plump Buck Mulligan came from the stairhead" puts wordcount(value) puts wordcount " " puts wordcount ""
10 8 0 0
Split notes. Split matches all possible parts of the string and returns an array of the results. It may not be intuitive to use split to count words, but this approach is effective.
String split
Info An iterator-based method could be faster. But this would also introduce further complexity into a program.
Iterator
String each char
When counting words, whitespace chars, along with punctuation, must be treated as non-word characters. We must consider them together, not alone—with the "\s+" pattern, we do this.
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 Nov 18, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.