Can someone explain this to me?


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 =
words.each {|word| frequencies[word] += 1}
frequencies = frequencies.sort_by {|a, b| b}


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), ...].


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!


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


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