To count the number of words in an array of strings in Ruby, you can use the split
method to break each string into an array of words, then use the size
method to count the number of words in each subarray. You can iterate through the main array, adding up the word counts of each subarray, to get the total word count of the entire array. Here's an example code snippet:
main.rb215 chars9 lines
This will output:
main.rb21 chars2 lines
Note that the split
method breaks each string into words based on whitespace, so it won't count hyphenated or compound words as multiple words. If you need to count those as multiple words, you'll need to modify the code to split on multiple delimiters.
gistlibby LogSnag