Sorting hashes in Ruby is an easy task. One does not have to design complex algorithms; instead, functions like sort
and sort_by
can be used to sort the hashes.
Hashes in Ruby are a collection of objects consisting of key-value pairs. It is essential to be able to sort these hashes when required for a program.
sort
functionThe sort
function in Ruby can be used to sort arrays and hashes. It takes the hash as input and returns a sorted hash.
The example below helps explain the sort
function.
hash = {"Samia":1, "Alpha":2, "Ali":3 }puts hash.sort # sorting the hash
In the code above, we first define a hash and then call the function sort
on hash
variable. The printed values indicate that the sort
function sorts the keys by default in alphabetical order.
sort_by
functionThe sort_by
function sorts a hash in a customized way. The sort_by
takes a function as input and returns a hash sorted by that function.
hash = {one:1, three:3, two:2 }puts hash.sort_by(&:last) ## sort by valuesputs hash.sort_by(&:first) ## sort by keys
In the code above, we define a hash named hash
. It contains numerical and alphabetical values. Using the sort_by
function, we first sort the hash according to its values using last
as a condition. It is clear as the puts
method prints 1
, 2
, and 3
in order.
After this, we use first
to sort the hash by its keys.
Free Resources