Help with iterating over an array in a histogram

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.chomp

words = text.split(" ")

frequencies =

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

frequencies = frequencies.sort_by {|a, b| b }


frequencies.each { |word, frequency| puts word + " " + frequency.to_s }

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.


Does it help if it is written using the alternative form
words.each do |word|
  frequencies[word] += 1

If not, which bit do you not understand?
1. words.each
2. do |word|
3. frequencies[word] += 1