6. Sort By


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

how does { |a, b| b } work?


a and b represent respectively the key and the value of the elements.

By using |a, b| we're telling sort_by with which variables we'll manipulate those. By stating simply b, we tell sort_by to sort according to the values. If we had stated a instead, it would have sorted by the keys.


Thanks, can you let me know which each triggers?

i also have it written as…

frequencies = frequencies.sort_by { |words, count| count }

But what I'm really trying to find is which line of code is it pulling from?
ie) is it referencing from frequencies = Hash.new(0) ???


I don't understand either of your questions.

Nothing is pulling from another line of code.

Are you asking if it's the same frequencies as the one defined in frequencies = Hash.new(0)?


I'm still not understanding |a, b|

How does it know what a and how does it know what b is?


It knows because that's how sort_by is defined.

sort_by expects a block, and in this block it expects two parameters, the first will be considered as the keys and the second will be considered as the values. I'm summarizing, I don't know the exact implementation of sort_by, we would need the code to know exactly what it does and how it does it, but fortunately we don't need all this, we just need to know how to use it.


OK great, for clarification, we are defining it on the spot?

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

in the above example, is |a,b| they keys, and b is the value?


We're only defining a block yes, and we're passing it to sort_by which knows what to do with it (assuming we ourselves know how to use sort_by ^^).

And no, in your example, a is the key, b is the value (inside |a, b|) and then we define what we want to do with a and b. In our case we only want sort_by to sort by value so we just give b (which represents the value). Again, if we had defined: {|a, b| a}, then the sort would have been made based on the keys.


OK great, thanks for taking the time to answer this. I think I somewhat understand, but will understand it more with practice. Thanks again!