Count words in string with hash


  • 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"


def count_words(string)
  words = string.split
  count =
  words.each { |word| count[word] += 1 }
  • Create a method that accepts a string argument.
  • Then use the split method to separate 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 every time we run into the word.
    • This looks for the current value in the hash and add 1 to it.