Learn
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
- In the example above, we create a new, empty hash
h
that has a default value of"nothing here"
. - Then we print out
{}
, the value ofh
, just to show thath
really is empty. - 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.
Instructions
1.
Create a hash called frequencies
in the editor.
Give it a default value of 0
.
After pressing Run, enter a message in the console and hit enter to check your code!
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.