rubyblockaccumulator

ruby blocks working code academy question


This query is about creating a histogram where user gives an input and we calculate the number of times a word has occurred

I am not able to understand the solution

input = "Hello how are you? I am fine how are you"

text = input.to_s



words = text.split

frequencies = Hash.new(0)



words.each do  |word| 

   frequencies[word] += 1 

end

p frequencies

Output

{"Hello"=>1, "how"=>2, "are"=>2, "you?"=>1, "I"=>1, "am"=>1, "fine"=>1, "you"=>1}
[Finished in 527ms]

In the above code we are calculating the frequency of each word. but where are we storing it in the frequencies hash?

which part of the code is doing that?

If i include a print statement inside the block it only gives the frequency.. so how is the word itself getting stored..

My apologies in advance if this is a silly question but i am not able to understand how the assignment is happening at the back end-- if we print it (inside the block), its displaying only the frequency..

Thanks in advance for helping out..


Solution

  • Adding the word to the hash and increasing the counter happens in the line

    frequencies[word] += 1
    

    and that only works because when the key does not exist yet then 0 is returned because of how the hash was defined in this line

    frequencies = Hash.new(0)
    

    Btw when you take advantage of Enumerable#tally then you can solve the whole problem in just only line:

    input.split.tally
    #=> {"Hello"=>1, "how"=>2, "are"=>2, "you?"=>1, "I"=>1, "am"=>1, "fine"=>1, "you"=>1}