Count words in string with hash

Problem

  • You want to count the number of words in a sentence and that sentence is stored as a string in a single variable.
string = "We only serve the freshest coffee to you in our cafes and on our webshop"

Solution

def count_words(string)
  words = string.split
  count = Hash.new(0)
  words.each { |word| count[word] += 1 }
  count
end
  • Create a method that accepts a string argument.
  • Then use the split method to seperate each word in the sentence and set it to a variable.
  • Create an empty hash with the default value of 0.
    • If you don’t do this the value would be nil, leading to an error.
  • As we iterate over every word add the key [word] to the hash count.
  • Then add 1 everytime we run into the word.
    • This looks for the current value in the hash and add 1 to it.