6. Sorting the Hash


6. Sorting the hash

im not sure whats wrong. I have read some other posts and a few work if i just copy and past them into my editor but they look close to my code. i would appreciate it if anyone could give me some input.

i read that the do in the frequencies = frequencies.sort_by do |x, y| is not needed but my code doesnt run if it is not there.


so i started from scratch and i found that it was this line ^^^ that was the problem. I re-wrote it to this

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

can anyone explain to me why in the example they show it as frequencies = frequencies.sort_by do |a, b|
then have one the next line the indicating sort vale b?

thank you

puts("please type something")
text = gets.chomp
words = text.split("")

frequencies = Hash.new (0)
words.each do |words| frequencies[words] += 1 

frequencies = frequencies.sort_by do |x, y|



You have a few different problems you don't need the parenthesis around the puts string, on your text.split("") you need to add a space in the quotations otherwise it will split all your characters up individually, which you don't want. second you have your words.each block a little mixed up. either do multiple line with do and an the 'end' keyword or do it one line without the do or end using curly braces instead:

so either

    words.each do |words|
    frequencies[words] += 1

words.each { |words| frequencies[words] += 1 }
you also have another issue with the each method you need to remove your sort_by method from the each block. also the sort_by block should be in curly braces not sure if you can invoke with the do keyword. then finally you need to output it .
after the changes you should have something resembling this:

puts "please add some text"
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new (0)
words.each {|words| frequencies[words] += 1 }
frequencies = frequencies.sort_by {|x, y| y}
frequencies.each {|word, frequency| puts word + " " + frequency.to_s }


hey cfecteau1 thanks your all your help and pointing out the other errors that i was unaware of. This really helps!



No problem best of luck to you