Sorting Hashes by Key
Ascending Order
Let’s say we had the following hash:
items = {
"b": 2,
"a": 3,
"c": 1
}If we wanted to sort it by keys, we can use the .sort method to sort in ascending order:
items = {
"b": 2,
"a": 3,
"c": 1
}
# sorting the hash by keys. `items` is now an array
items = items.sortThe code above will result in items being an array of arrays (sorted alphabetically by keys) that looks like this:
[[:a, 3], [:b, 2], [:c, 1]]Descending Order
To sort a hash by key in descending order, we can chain the .reverse method to the previous code:
items = {
"b": 2,
"a": 3,
"c": 1
}
items = items.sort.reverseThe code above turns items into the following:
[[:c, 1], [:b, 2], [:a, 3]]Sorting Hashes by Value
Ascending Order
To sort a hash by value, we need to use .sort_by like so:
items = {
"b": 2,
"a": 3,
"c": 1
}
# sorting by values
items = items.sort_by { |k, v| v }The code above will result in items being an array once again, but this time sorted by values in ascending order:
[[:c, 1], [:b, 2], [:a, 3]]Descending Order
We can also use .sort_by to sort values in descending order by using -v:
items = {
"b": 2,
"a": 3,
"c": 1
}
# sorting by values in descending order, note the `-v`
items = items.sort_by { |k, v| -v }The code above transforms items into the following:
[[:a, 3], [:b, 2], [:c, 1]]Side Note: Converting Resulting Arrays to Hashes
As a side note: if you still need the result in a hash format, you can convert the resulting array into a hash with .to_h:
items = {
"b": 2,
"a": 3,
"c": 1
}
# sorting and converting the result to a hash
items = items.sort.to_hThe code above will result in items being a hash again:
{:a=>3, :b=>2, :c=>1}