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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.