6. Sorting the Hash // undefined method `reverse!' for {}:Hash


#1

Hi funny fellows!

I'm experiencing many troubles with the following code, which is, I think a valid one.
I've got the error message : "undefined method `reverse!' for {}:Hash" which is unfortunate, because even the example code is not working.

puts "Text please: "
text = gets.chomp

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

Any advice?

Thanks for answering :wink:


#2

Reversing requires there being order. Your variable frequencies is a hash, and that data type does not represent order, and so it doesn't make sense to reverse it. There's nothing to reverse. You can grab the key-value pairs and put them into an array in order. But doing so will not do anything to the hash, you just read from it. You would need to reverse that array instead. So where do you have that array in your code?


#3

Actually, I've perfectly understood what you are saying, thanks, it's just confusing that the example is actually the same code than mine :slight_smile:

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 }

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.