Sorting the Hash


#1

Apparently I have not set up the Hash properly. I can't see what is wrong with my code (however as a total beginner that does not surprise me!). Can you help please?

puts "write some text"
text = gets.chomp

words = text.split("")

frequencies = Hash.new(0)
words.each do |words| frequencies[words]+=1
frequencies = frequencies.sort_by do |frequencies, count|
end
frequencies.reverse!
end

#2

Firstly, you might wanna split the text into words, ex. "This is some text" - if you want to get its words, you should split(" ").
Secondly, these lines:

words.each do |words| frequencies[words]+=1
  frequencies = frequencies.sort_by do |frequencies, count|
end

are wrong. You need to assign frequencies first, then sort them.

words.each { |word| frequencies[word] += 1 }
frequencies = frequencies.sort_by {|a, b| b }

And then reverse them in place. Hope it helps, next time make sure to link to your exercise.


#3

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