Setting a Default Value in Hash

Learn how to set default values in a hash in Ruby.

Interview question

It is often useful to have default values in a hash. We might even want to make a bookmark since we can use this trick while solving interview questions. We’ll take a look at one of these questions.

Given a sentence, calculate the usage frequency for each word. For example, there are two “the” words in the sentence, one “dog,” and so on. How do we solve this problem?

Imagine we have the string "the quick brown fox jumps over the lazy dog". Let’s split this string into an array, so we have an array of words for this sentence:

str = 'the quick brown fox jumps over the lazy dog'
arr = str.split(' ')   

We now have an array of words in the arr variable. Let’s traverse the array and put each element into a hash, where the hash key is the word itself and the value is the counter. As the first step, we will just set this counter to a single 1 for every word:

hh = {}
arr.each do |word|
  hh[word] = 1

However, we don’t want to set the counter to a single 1 since we want to calculate the number of occurrences of every word in a sentence. So, we need to increase the counter by one. We can just use hh[word] += 1 or hh[word] = hh[word] + 1 because if the word is not present in the hash, we’ll get the following error:

NoMethodError: undefined method '+' for nil:NilClass

In other words, the plus operation isn’t applicable to nil. So we need to perform a comparison: if the word is already in the hash, increase the counter by one. Otherwise, add this word with initial counter value, which is 1:

arr.each do |word|
  if hh[word].nil?
    hh[word] = 1
    hh[word] += 1

Here is what a full application listing would look like:

Get hands-on with 1200+ tech skills courses.