6. Sorting the Hash - no reverse result

Hello :slightly_smiling_face:

I guess something is wrong with the code, although the exercise is validated, because my words are not appearing in any specific order ( ascendant or descendant), only by the order as they appear in the sentence.

This is my code :

puts "Your text here : "
text = gets.chomp

words = text.split (" ")

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

puts frequencies ["rate"]
# 0

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

And this is the result I get :

 Your text here : 
racoon racoon elephant potato tomato tomato tomato
{"racoon"=>2, "elephant"=>1, "potato"=>1, "tomato"=>3}
0

I tried without the frequencies.reverse!, and I get the exact same result.

Can someone help me to see whatโ€™s wrong ?

Thank you !

Sorting the Hash

Your text here : 
 racoon racoon elephant potato tomato tomato tomato
{"racoon"=>2, "elephant"=>1, "potato"=>1, "tomato"=>3}
=> [["tomato", 3], ["racoon", 2], ["potato", 1], ["elephant", 1]]
   

Note that frequencies is no longer a hash, but an array of tuples in the form of key value pairs. They are sorted by values.

So, I should change something in the code to get the correct result ?

Nothing to change, your code is giving the correct result. The next lesson has us print it out so as long as your code is accepted, move on to the next step.

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