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

If you have a hash with a default value, and you try to access a non-existent key, you get that default value.



Create a hash called frequencies in the editor.

Give it a default value of 0.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?