Create a Histogram, don't quite understand a line


#1



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


My code actually behaves correctly but I don't understand the code on line 8, what is the purpose of this "count" on it ? This is surely a small thing to be worried about but I'm trying to understand everything in detail.


puts "Write something please."
text = gets.chomp

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


#2

You should look at this with the broader perspective, this is a single block:

frequencies = frequencies.sort_by do |word, count| 
    count
end

It basically says that we want to sort our hash frequencies by count (this is the answer to your question) where word is a key and count is a value.

Thanks to that in the result (after reversing) words that are most frequent will be at the beginning of the hash.

Try to pass as an input: "first second third first second first". The result is:

[["first", 3], ["second", 2], ["third", 1]]

#3

Oh I get it. count is the placeholder for the value(count) assigned to a key(word) and it is directly connected to the .sort-by method because it tells the method how to sort the text.

Thanks for the help :slight_smile:


#4

Exactly! :slight_smile: You're very welcome.