Sorting Hash!


#1

----- my code -----
puts " Input a Number: "
text = gets.chomp

words = text.split (" ")

frequencies = Hash.new (0)

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

frequencies = frequencies.sort_by { | 0 , 100 | 100}

frequencies.reverse!


can somebody explain me this stuff im stuck here

---- INSTRUCTIONS -----
Use .sort_by to sort the frequencies hash by word count, like step 2 above. Store the result back in frequencies.
Use .reverse! to reverse the sorted frequencies array.
Check the Hint for more details!

Our first step should be to reassign frequencies to its sorted version (.sort_by doesn't sort the hash in-placeā€”it will create a copy that is sorted):

frequencies = frequencies.sort_by { |k, v| v }
This actually returns an array of values, which you can then reverse in-place with reverse!:

frequencies.reverse!

---- THATS THE HINT ------

----- THIS IS THE ERROR ----
(ruby):9: syntax error, unexpected tINTEGER, expecting '|'
frequencies = frequencies.sort_by { | 0 , 100 | 100}
^


#2

0 and 100 are numbers when they should be variables. Use any you like. Eg. |a , b| b.


#3

thanks man hold on ,

requencies = frequencies.sort_by { | 0 , 100 | 100}
0 and 100 are numbers when they should be variables. Use any you like. Eg. |a , b| b.

Reply
This topic will close 7 days after the last reply.


#4

thanks man that solves the problem


#5

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