Understanding Hash and how the key=>value works




I’m working on the Histogram and feel absolutely lost.
I get different errors, I’m having trouble understanding the idea so I can’t implement it well.
From what I understand a Hash will create a group of relationships between a key and a value. I think technically it can be empty and not do what it’s supposed to until I fill it.
When I create
frequencies= Hash.new(0)
what role does the 0 play in the Hash- it’s not a key or a value?
Thank you

Replace this line with your code. 


At the moment this line is executed, frequencies is an empty hash, {}. The new(0) tells Ruby that whenever a new key is added to the hash, set its value to 0 so that it can be incremented. (It needs to be a number). As subsequent encounters with words in the hash come about, those word’s value is incremented by 1. This way we get a complete count of all the words and their occurrences.


Thank you!
Let me ask to make sure I understand-
If I don’t increment after crating the hash, then every word would be set to 0?


Every new key will have a value of zero, by default.

frequencies[word] += 1

We can only do this because the value is initialized to 0.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.