Can somebody help me on this one and try to explain this to me?


#1

Here is my code :slight_smile:

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!

---- 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!

?
Hint
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!


#2

What does this line mean:

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

?

You have the correct code in the hint, so I don't really know why you have used 0 and 100. Please explain why you modified this line and I will explain what's wrong.


#3

this has been solved I understand now instead of using numbers as your variable use a string instead


#4

ok i have an problem here:

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

what does this line do exactly?
i am pretty sure that "a" stands for the words and "b" for the number connected to the word but what does the second "b" do?


#5

This line says sort frequencies by b (second b) where a is a key and b is a value (|a, b|). So, in other words, it simply sorts frequencies by the values.


#6

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