A hash or a dictionary (in other programming languages) refers to a data structure that stores data in key-value pairs. Each key in a hash must be unique and can be of any valid Ruby data type.
Hashes are incredibly useful and can save you a lot of time and code when used appropriately. Although they tend to behave like arrays, hashes use unique keys instead of integer positions. Think of hashes as a real dictionary where each key is unique and holds a corresponding meaning or value.
In this guide, we will learn how to sort a hash in Ruby using various methods. No, we will not use fancy algorithms or benchmarks. We will focus on built-in Ruby sorting methods.
Ruby Hash – The Basics
Creating a hash in Ruby is very straightforward. You start by defining a key followed by the => symbol and the value. We enclose items in a hash in a pair of curly braces.
You can add multiple key-value pairs by separating them using commas:
Ruby also supports another format to create a hash. Instead of using rocket notation =>, you can use colons.
Regardless of which method you use to create a Ruby hash, the Ruby interpreter will recognize them as valid hashes.
If you would like to learn how to work with Ruby hashes, consider the tutorial:
https://linuxhint.com/how-to-use-ruby-hashes/
Sorting Hashes in Ruby
To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by.
Using the built-in methods, we can sort the values in a hash by various parameters.
Let us discuss:
#sort
The first method to use when sorting a hash is the sort method. The sort method returns an array of the sorted values. It works by comparing the values using the <=> operator.
Example 1
Consider the example hash below:
state_info.sort
Once we call the sort method against the hash, it will return the keys sorted in alphabetical order.
You will notice that the result from the sorted hash is in the form of a multi-dimensional array. As mentioned, the sort method returns an array of the sorted values.
To access the sorted key-value pairs, you can use the index notation.
sorted_state[0]
["Georgia", 41]
Example 2
Let us consider a scenario where we need to sort the hash by the values instead of the keys.
Unfortunately, there is no direct way to sort the hash by keys. However, we can use the values method to fetch the hash values and sort them.
Take a look at the example below:
Once we execute the above command, we should get the values of the hash sorted in array format.
Example 3
The values of the sort method are of array type. We can switch them back to hash by using the to_h method.
Look at the example below:
state_info.sort.to_h
The example above will return the hash sorted as:
#sort_by
In example 2, we implemented a simple way to sort the hash by values. However, there is one drawback: we only sort the keys and not the keys.
To resolve this, we can dive into using the sort_by method.
Example 1
Consider the state_info hash from the previous methods:
Using sort by, we can perform the following operation:
You will notice the method uses Ruby blocks to sort the values in the specified order. Check our tutorial on Ruby do to learn more.
The resulting value is:
So+++rting of the values from the resulting array is in ascending order. In this example, we include both the keys and their corresponding values.
Similarly, you can revert the result to a hash:
{"Georgia"=>41, "Indiana"=>45, "Idaho"=>72, "Massachusetts"=>78}
Example 2
By default, the sort methods in Ruby will sort by ascending order. To get the sorted values in reverse order, we can call the #reverse method.
state_info.sort_by {|k, v| v}.reverse
[["Massachusetts", 78], ["Idaho", 72], ["Indiana", 45], ["Georgia", 41]]
Example 3
Suppose we have a nested hash. How do we sort the values inside the nested hash?
Consider the following example hash:
"Massachusetts" => {"abr" => "MA", "fips_code" => 25},
"Idaho" => {"abr" => "ID", "fips_code" => 16},
"Georgia" => {"abr" => "GA", "fips_code" => 13},
"Indiana" => {"abr" => "IN", "fips_code" => 18}
}
To sort the hash by the values of the nested hash, we can do a sort_by as shown:
The resulting values are as:
["Idaho", {"abr"=>"ID", "fips_code"=>16}],
["Indiana", {"abr"=>"IN", "fips_code"=>18}],
["Massachusetts", {"abr"=>"MA", "fips_code"=>25}]]
As this example shows, the results print out sorted in ascending order of the values in the nested hash.
Conclusion
Using this tutorial, you looked at how to use the sort and sort_by methods to sort a hash in Ruby. Using this guide, you can write short and more efficient ruby code.