count words in array in ruby

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.rb
array_of_strings = ["Hello world", "This is a test string", "Ruby programming is fun"]
word_count = 0

array_of_strings.each do |string|
  word_count += string.split.size
end

puts "Total word count: #{word_count}"
215 chars
9 lines

This will output:

main.rb
Total word count: 10
21 chars
2 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