Understanding |word] with hash


#1

<PLEASE USE HI,

I would really appreciate some help to understand the code- not just write it properly.

frequencies = Hash.new(0)
words.each do |word| frequencies[word] += 1
end

I am confused about using “word” twice in the code. the |word] declares the name/ is a placeholder for the iterating through “words” then the frequencies[word] is declaring the the key in the frequencies hash to be “word” and the value will incremement by 1
but why is word used twice and how do they relate to one another?
Thanks!



. 



#2

Exactly. It is what is known as the block parameter.

Except for the quotes, that too is correct. The hash is initialized to 0 in the Hash.new statement. word is a string (a word) and each time it is encountered, its count is increased by one.

|param|           =>  between pipes

frequencies[key]  =>  written as a subscript

#3

Thank you!
OK - I think im getting it, but why do you say word is a string? What I
think Im seeing is that frequencies[word] declares that the key is word but
not word as a string but rather word as in iteration through all the words.
Is that right?

I also dont understand why in the following code you need the final b- what
does that add?:

frequencies = frequencies.sort_by {|a, b| b }
Im going over this and i guess .sort_by is always for a hash so the pipes
always are filled with 2 components |a,b| and then it has to follow with
how you are sorting - either a or b?

THANKS SO UCH FOR YOUR HELP! YOU ARE SO CLEAR!

http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail
Virus-free.
www.avg.com
http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>


#4

Because it is. word is a variable representing a data type belonging to the class, String. We start with a string, then split it into an arrray of strings, then read them off, one at a time, as strings. As each string is encountered it is accumulated, or added to the hash and given an increment.

And that would be correct. a and b are key and value parameters, respectively. We are sorting this hash by values.


#5

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