Hash.new: how do frequencies keys gets defined in Unit 4 exercise 7?


#1

Hello everyone!

I just started to learn coding and I am having trouble understanding how the exercise 7 works:
Basically I got how we assigned a number to each word of the text, but I don't get how frequencies got defined by the words in the text from line 6 to line 7?
How did we assign the words into the empty hash?
I don't know if my question is clear...but I really want to understand :slight_smile:
Thank you!

1    puts " write a text"
2    text=gets.chomp
3    words=text.split
4    frequencies=Hash.new(0)
5    puts frequencies ["dog"]
6    words.each {|x| frequencies[x]+=1}
7    frequencies=frequencies.sort_by do |x,count|
8        count
9    end
10  frequencies.reverse!

#2

If you're asking how you can add 1 to a key that does not exist yet, then the answer is that they get created at that time with the default value that you specified when creating the hash (0)

Documentation for Hash::new:
http://ruby-doc.org/core-2.2.0/Hash.html#method-c-new
(Says that the argument becomes the default value and has an example demonstrating that)


#3

Thanks for replying :slight_smile
and thanks for the link!

Its not how we assigned numbers to the keys, Its how we assigned the keys to the empty hash. When we created the empty hash it already has a default numbers for empty spaces: How did we assign the keys to these empty spaces? How did frequencies hash got filled with the words we gets.chomped and split?
At no point we had something that would mean frequencies={ word1, word2,word3...}

Sara


#4

The default value is 0, so that what you get when you look something up that doesn't exist.

When you change the value (like adding 1), it (the Hash data structure) will create that key-value pair.

For example (interactive ruby shell):

> my_hash = Hash.new(0)
> puts my_hash
{}
> my_hash['hello'] += 1
> puts my_hash
{"hello"=>1}

#5

oooooh got it !
Thank youuuu :grin:


#6

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