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.
# Step 2: split string based on one or more whitespace characters.# ... Then return the length of the array.
# Step 1: specify the string.
value = "To be or not to be, that is the question."
value = "Stately, plump Buck Mulligan came from the stairhead"
puts wordcount " "
puts wordcount ""10
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.