One possible solution to count the occurrences of each word in the given string is by using regular expressions and a hash in Ruby.
Here's an example code snippet that achieves this:
main.rb447 chars19 lines
Output:
main.rb35 chars6 lines
In this solution, we first convert the entire text to lowercase to treat words case-insensitively. Then, we use the scan
method with a regular expression (/\b\w+\b/
) to split the text into an array of words. The regular expression \b\w+\b
matches each word in the text.
We then iterate over the array of words, update the counts in the word_counts
hash, and increment the count for each occurrence of a word. Finally, we output the word counts by iterating over the hash and printing each word along with its count.
Note: The code treats words like ta're
as separate from words like ta
or re
, as they are different words even though they are contracted.
gistlibby LogSnag