Ruby

Sort Hash Ruby

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.

{"key" => "value"}

You can add multiple key-value pairs by separating them using commas:

{"MS" => "Massachusetts", "ID" => "Idaho", "GA" => "Georgia", "IN" => "Indiana"}

Ruby also supports another format to create a hash. Instead of using rocket notation =>, you can use colons.

{"MS": "Massachusetts", "ID": "Idaho", "GA": "Georgia", "IN": "Indiana"}

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 = {"Massachusetts" => 78, "Idaho" => 72, "Georgia" => 41, "Indiana" => 45}
state_info.sort

Once we call the sort method against the hash, it will return the keys sorted in alphabetical order.

[["Georgia", 41], ["Idaho", 72], ["Indiana", 45], ["Massachusetts", 78]]

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 = state_info.sort
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:

state_info.values.sort

Once we execute the above command, we should get the values of the hash sorted in array format.

[41, 45, 72, 78]

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 = {"Massachusetts" => 78, "Idaho" => 72, "Georgia" => 41, "Indiana" => 45}
state_info.sort.to_h

The example above will return the hash sorted as:

{"Georgia"=>41, "Idaho"=>72, "Indiana"=>45, "Massachusetts"=>78}

#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:

state_info = {"Massachusetts" => 78, "Idaho" => 72, "Georgia" => 41, "Indiana" => 45}

Using sort by, we can perform the following operation:

state_info.sort_by {|k, v| v}

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:

[["Georgia", 41], ["Indiana", 45], ["Idaho", 72], ["Massachusetts", 78]]

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:

state_info.sort_by {|k, v| v}.to_h
{"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 = {"Massachusetts" => 78, "Idaho" => 72, "Georgia" => 41, "Indiana" => 45}
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:

 states = {
"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:

states.sort_by { |k, v| v["fips_code"] }

The resulting values are as:

[["Georgia", {"abr"=>"GA", "fips_code"=>13}],
["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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list