What is this code


puts "Text please: "
text = gets.chomp

words = text.split(" ")
frequencies = Hash.new(0)
words.each { |word| frequencies[word] += 1 }
frequencies = frequencies.sort_by {|a, b| b }
frequencies.each { |word, frequency| puts word + " " + frequency.to_s }

Everything works, but where i'm lost is what it is i'm doing here. I know what the result will be, but I don't know how I got there.

Could someone just briefly walk through this code with me. Specifically

words.each { |word| frequencies[word] += 1 }
frequencies.each { |word, frequency| puts word + " " + frequency.to_s }

these two lines here. So it seems like we are taking an array, and splitting it up and adding info to it. But i'm just confused about why it's displayed like this I guess.


At this point, words is an array containing our different words. We scan through this array using each. Each element is then used as key and inserted into the hash frequencies, and the corresponding value is increased by 1 (all values are 0 by default, see the creation of our hash above). If we have two identical words, then we will access the same key twice and will therefore increase our corresponding value twice.

We scan through our hash (already filled), and we display each key and its corresponding value (using temporary variables word and frequency).