6. Sorting the Hash


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-693PD/0/6?curriculum_id=5059f8619189a5000201fbcb#

the code says:
Oops, try again. It looks like you haven't set the frequencies hash correctly. Check the first exercise if you need help!

and:
undefined method `|' for {}:Hash

text = puts "what text would you like?"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each{|x|
frequencies = frequencies|x| + 1
frequencies = frequencies.sort_by do |frequencies, count|
    count
end
frequencies.reverse!
}


#2

There are just a couple of issues in your code:

  1. Your words.each function should end once it has added each word and increased the count in "frequencies" - sorting and reversing should take place after the word counts are input.

  2. In the words.each function, your code has frequencies set to equal frequencies[word] + 1 so there's a mismatch there as you want to target frequencies[word] not the main frequencies hash. You've also used pipes instead of square brackets.

The tidiest way to express this would simply be: frequencies[x] += 1

text = puts "what text would you like?"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each{|x| frequencies[x] += 1 }
frequencies = frequencies.sort_by do |frequencies, count|
    count
end
frequencies.reverse!

#3

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