Hey Calvin.
This line iterates through words array and counts how many times each word is there. Here how it works:
Let's say you have words = ['never', 'say', 'never']. Your frequencies is an empty hash right now: {}.
In your line we start to iterate and take the first word never and we use it to access or create element in our hash: frequencies['never']. As we don't have such an element in our hash yet, new element is created and initialized with 0 and then we add 1 to it. So after first iteration our frequencies hash looks like this: { 'never' => 1 }.
The same thing happens with 'say' word and frequencies now looks like this: { 'never' => 1, 'say' => 1 }.
And then we encounter 'never' again. There is such key in our hash so frequencies['never'] gets value (which is 1 now) and then adds 1 to it, so the resulting hash: { 'never' => 2, 'say' => 1 }.
Hope that helps.
Cheers,
Rem.
--Hello there,I am currently going through the Ruby course in Codeacademy and we are going over histograms. There is a particular exercise (5/8 of Data Structures, Meet Iteration) that is giving me trouble. I do not understand the line of code that is in bold below. I've gone through the exercise description a few times and looked around on the forums, but I don't understand what that line is doing. I was hoping someone could explain it to me in their own words - maybe that'll help?puts "Text please: "text = gets.chompwords = text.split(" ")frequencies = Hash.new(0)words.each { |word| frequencies[word] += 1 }frequencies = frequencies.sort_by {|a, b| b }frequencies.reverse!frequencies.each { |word, frequency| puts word + " " + frequency.to_s }
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/c249f5fa-f018-47b3-921c-564f43ed12ba%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAPP9BSH92b7O6SjOgGJeLT7v7sU3%2BYErVux3WyOB4rR8hxEfeg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment