puts "Please put word to be added"
text = gets.chomp
words = text.split

frequencies = Hash.new(0)

words.each { |word| frequencies [word] += 1 }

I`m currently learning step 5 iterating over an array
If I may understand from the step above, the hash will AUTOMATICALLY add new key taken from the split of variable words ?
Which step that causes this automatic key addition ? Is it the each ?

I don`t really understand the AUTOMATIC logic of this new key addition in the hash…

Sorry if my question is really basic…

Thank you


This should be a phrase or large block of text. We are not adding a word.

This is normal hash behavior. When we wish to add a key-value pair to the hash, we simply subscript the key, and assign the value.

 my_hash["key"] = value

In the block above, word is the key, Ruby is told to initialize all new keys with the value 0, which permits the compound assignment in the each block. each has no hand in how the new keys are added to the hash. The hash class has its own methods to look after insertion of items.


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