7/8 Iterating over the hash


#1

This does not work:
puts "Enter text please: "
text = gets.chomp
words = text.split(" ")
frequencies=Hash.new(0)
words.each = {|word| frequencies[word] += 1 }
frequencies = frequencies.sort_by {|word, count| count}
frequencies.reverse!

frequencies.each do |word, frequencies|
puts word + " " + frequency.to_s

Why???


#2

Couple of corrections required:

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

frequencies.each do |word, frequencies|
#                           frequency

The puts line that follows needs to be indented four spaces
Ruby expects end to close the do

Corrected code as follows:

puts "Enter text please: "
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each {|word| frequencies[word] += 1 }
frequencies = frequencies.sort_by {|word, count| count}
frequencies.reverse!

frequencies.each do |word, frequency|
    puts word + " " + frequency.to_s
end

Aside: Please preface and follow code samples with three back-ticks on their own line. This will preserve the indentation and format and make it readable.


#3

Thank You for the explained solution. Now it works! :grin: