This coding exercise examines how to properly count the total number of words in Ruby. Additionally, we’ll walk through how to breakdown the counts for each specific word in a string.
Summary
Use monkeypatching on Ruby’s String class to implement two methods. One that properly counts the total number of words in a string. The method should count the occurrences of each specific word in a string.
Exercise File
Exercise Description
Given the following string:
'- the quick brown fox / jumped over the lazy fox.'
Add two methods to the String class that: count the total number of words in a string (make sure to not count punctuation as words), and counts how many time each word was used (returned as a hash).
Sample Output Given Sample Input
Total Words
9
Total Words
{ "the"=>2, "quick"=>1, "brown"=>1, "fox"=>2, "jumped"=>1, "over"=>1, "lazy"=>1 }
Real World Usage
This process is used in many situations, especially scenarios involving content management. Additionally, these are common Ruby coding interview questions.
Solution
Can be found on the solutions branch on github.
I was once nailed in an interview with this exact question – thanks!
I’m glad that you found it helpful!