Histogram - Explaining this bit of code


#1

Can someone please explain this code? I've gotten up to here but I am still confused as to what gets.chomp exactly does along with text.split, and the loops. ex. words.each... { and how everything in between these are built }. Help anyone?

Thanks!

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.reverse!
frequencies.each { |word, frequency| puts word + " " + frequency.to_s }


#2
gets            => gets input

Keyboard input will be "text"+"\n" (new line escape sequence)

chomp           => truncate

The text will now be just text.

text.split(" ") => construct a new array of words

The " " (space) character is the separator so will not be stored in the array.

Once a new hash is defined, it is populated with a shortened list of all the words, and their occurances are recorded by count. The loop iterates through all the words, one at a time, and either adds it to the hash as a key with a value of 1, or If the key already exists, its value is incremented.

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

The resulting hash is not ordered. The next line sorts the data by value, in ascending order. To store the sorted list, Ruby creates a new array of tuples. frequencies is now an array, and the hash is no longer in existence.

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

To store the list in descending order, we use the reverse! method. The ! modifier tells Ruby to do it in place.

frequencies.reverse!

The last loop iterates the frequencies array, one tuple at a time. Ruby copies the first member of the tuple to the word variable, and the second to the frequency variable. The frequency is a number which cannot be concatenate to a string, so it is converted to a string with the to_s method.

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

#3

If you put in this code, it'll visually show your what mtf explained. I was confused to. Hope this helps...

puts "Type a sentence with word repeats"
text = gets.chomp

words = text.split (" ")

frequencies = Hash.new (0)

puts frequencies

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

puts frequencies

frequencies = frequencies.sort_by do |word,number|
number
end
puts frequencies

frequencies.reverse!

puts frequencies

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