Understanding Hash and how the key=>value works


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

https://www.codecademy.com/courses/learn-ruby/lessons/create-a-histogram/exercises/creating-the-frequencies-hash?action=lesson_resume

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. 



#2

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.


#3

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?


#4

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.


#5

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