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.
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.
string
in which we want to count words. We consider 4 strings in total.split()
. We return the length of matches.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
notesSplit
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.
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.