Purpose of a default value/empty hash?

Taken from Intro to Ruby . . .

Creating the Frequencies Hash

Good! Now we’ll start counting words using a hash.

We’ll want to make sure the hash has a default value.

h = Hash.new(“nothing here”)
puts h


puts h[“kitty”]

nothing here

  1. In the example above, we create a new, empty hash h that has a default value of "nothing here".
  2. Then we print out {}, the value of h, just to show that h really is empty.
  3. Then we print out nothing here as we try to access the value stored by the key "kitty".

Whats the purpose of a default value and/or empty hash? Are they the same thing. I’m a beginner, so please simplify your answer as best you can.

Thanks, C

Step 4 would be to print h again. One will discover that Ruby has created the key `‘kitty’ and assigned the default value.

Default values can be anything, depending on the intended role of the hash. For this exercise we are going to be doing arithmetic on the value so use 0 as the default value. Now we are able to define new keys on the fly and immediately increment them.

1 Like