Ruby Hash#sort_by

Ruby#sort and #sort_by methods are powerful: We can easily arrange the result we want, such as sort the names by alphabetical order or the name?s length. Surprisingly, there are not many examples in Ruby document library for this useful tool. Therefore, I would like to explore some use cases of #sort_by and #sort, specifically for Hash.

  • #sort will return a new array

First thing to note that #sort/#sort_by will return a new array. Suppose we have a hash:

hash = {a:1, b:2, c:4, d:3, e:2}

When we call sort on this hash, it will convert hash into a nested array:

hash.sort=> [[:a, 1], [:b, 2], [:c, 4], [:d, 3], [:e, 2]]

Therefore, if we want to return the sorted hash in hash format, we need to call #to_h after #sort.

Sort by Hash values in ascending and descending order

So what if we want to sort by hash values instead of the key?s order? Here comes the #sort_by method:

hash.sort_by {|k, v| v}=> [[:a, 1], [:b, 2], [:e, 2], [:d, 3], [:c, 4]]

By default, Ruby returns the value in ascending order. If we want Ruby to return the value in descending order without using #reverse method, we can do this:

hash.sort_by {|k, v| -v}=> [[:c, 4], [:d, 3], [:b, 2], [:e, 2], [:a, 1]]

Sort by Hash values and keys at the same time

Finally, suppose we have a long list of hash like below:

hash = {?w?=>2, ?k?=>1, ?l?=>2, ?v?=>5, ?d?=>2, ?h?=>4, ?f?=>1, ?u?=>1, ?p?=>1, ?j?=>1}

With this hash, we want to do two things. First, sort the hash by the values in descending order . Then, sort it by letter?s alphabetical order. We can easily achieved this as below:

hash.sort_by {|k, v| [-v, k]}=> [[?v?, 5], [?h?, 4], [?d?, 2], [?l?, 2], [?w?, 2], [?f?, 1], [?j?, 1], [?k?, 1], [?p?, 1], [?u?, 1]]

I hope the use cases will help us write cleaner and shorter codes in Ruby.

20