Understanding Sort By


Hello. i am having problem understand how does sort by function works.

frequencies = frequencies.sort_by do |a,b| b

i am unsure what does |a,b| b means. I think a is key , 1st b is value . But i dont understand what does the last b means

 puts "input text please"
text = gets.chomp

words = text.split(" ")

frequencies = Hash.new(0)

puts frequencies

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

frequencies = frequencies.sort_by do |a,b| b


@digitalwhiz67993 ,

This block is what you are passing to the frequencies.sort_by method ...

do |a, b| b

The outcome is that frequencies gets sorted by the values, which represent the frequencies of the occurrences of the words.

Afterwards, this ...


... reverses the order of the items in frequencies, so the words that occur the most often will occur first in the result.


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