Can someone explain this to me?


#1

Can someone explain to me this line from the code below

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

I completely understand the other things, just that one.. i know that |a, b| b are blocks and sort_by is a function but what exactly is happening??

puts "Type  a anything!"
text = gets.chomp

words = text.split(",")


frequencies = Hash.new(0)
words.each {|word| frequencies[word] += 1}
frequencies = frequencies.sort_by {|a, b| b}
frequencies.reverse!

#2

sort_by takes a hash with key and value pairs ( |a, b| above) and orders them by key or value as specified. The above will be by sorted by value. The result is an array of tuples. [(key, value), (key, value), ...].


#3

That was my first guess. I was having trouble earlier because when i substitute the b with the a , it doesn't go alphabetical , the reason is because of the frequencies.reverse! reversing it. thanks for the reply!


#4

Since this is a histogram (frequency table) we are sorting by count, not by alphabet.


#5

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