Sorting Hashes by Key
Ascending Order
Lets say we had the following hash:
| |
If we wanted to sort it by keys, we can use the .sort method to sort in ascending order:
| |
The code above will result in items being an array of arrays (sorted alphabetically by keys) that looks like this:
| |
Descending Order
To sort a hash by key in descending order, we can chain the .reverse method to the previous code:
| |
The code above turns items into the following:
| |
Sorting Hashes by Value
Ascending Order
To sort a hash by value, we need to use .sort_by like so:
| |
The code above will result in items being an array once again, but this time sorted by values in ascending order:
| |
Descending Order
We can also use .sort_by to sort values in descending order by using -v:
| |
The code above transforms items into the following:
| |
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:
| |
The code above will result in items being a hash again:
| |