5/8 Need help understanding


Hello, i'd be grateful is somebody could help me understand this bit of code!

words = text.split(" ")

frequencies = Hash.new(0)

words.each do | word |
frequencies[word] += 1

I don't quite understand what you are doing with frequencies
A. To begin with by setting Hash.new(0)
B. What we are accomplishing later by adding frequencies[word] += 1

It's completely lost on me in the text used on the tutorial and it would be extremely helpful is someone could explain it to me in a different way.

Thank you.



frequencies = Hash.new(0) creates a new hash. The 0 is the default value, that is the value a key has if it was not set to anything before.

frequiences[word] += 1 increases the value of the key stored in word.

So if for example word takes on the value "Ruby", frequencies[word] += 1 increases the "Ruby" key's value by one. There is the possibility that the "Ruby" key is accessed for the first time, that's why the default was set to 0.