How To Sort Hash By Value In Ruby

Sorting a hash by value is a common task when working with data structures in Ruby. In this blog post, we will explore how to sort a hash by value in Ruby, both ascending and descending order, and learn some tips and tricks for dealing with more complex data structures.

Sorting a Hash by Value – Ascending Order

Let’s start by looking at a simple example of sorting a hash by value in ascending order. Suppose we have the following hash containing the scores of different players in a game:

scores = {
“Alice” => 50,
“Bob” => 80,
“Cathy” => 30,
“Dan” => 70
}

In order to sort this hash by the scores (values), we can use the sort_by method from Ruby’s Enumerable module. The sort_by method accepts a block in which we can specify the criteria for sorting. In this case, we want to sort by the values, so we can use the following code:

sorted_scores = scores.sort_by { |player, score| score }

The sorted_scores variable will now contain an array of arrays, with each inner array containing the key-value pair. The resulting array will look like this:

[[“Cathy”, 30], [“Alice”, 50], [“Dan”, 70], [“Bob”, 80]]

If you want to convert this back to a hash, you can use the to_h method:

sorted_hash = sorted_scores.to_h

Sorting a Hash by Value – Descending Order

If you need to sort the hash in descending order, you can simply add a reverse method call after the sort_by method:

sorted_scores_desc = scores.sort_by { |player, score| score }.reverse

The resulting array will now be sorted in descending order by the values:

[[“Bob”, 80], [“Dan”, 70], [“Alice”, 50], [“Cathy”, 30]]

Sorting a Hash by Value with Complex Data Structures

The previous examples showed how to sort a simple hash by value. But what if you have a more complex data structure where the values are themselves hashes or arrays? In such cases, you can modify the block passed to the sort_by method to suit your specific needs.

For example, let’s say we have a hash where the keys are movie titles, and the values are hashes containing information about the movie, such as the director and release year. If we want to sort this hash by the release year, we can do this:

movies = {
“The Godfather” => { director: “Francis Ford Coppola”, year: 1972 },
“Pulp Fiction” => { director: “Quentin Tarantino”, year: 1994 },
“The Shawshank Redemption” => { director: “Frank Darabont”, year: 1994 },
“Schindler’s List” => { director: “Steven Spielberg”, year: 1993 }
}

sorted_movies = movies.sort_by { |title, info| info[:year] }

The sorted_movies array will now be sorted by the release year of the movies, in ascending order:

[
[“The Godfather”, { director: “Francis Ford Coppola”, year: 1972 }],
[“Schindler’s List”, { director: “Steven Spielberg”, year: 1993 }],
[“Pulp Fiction”, { director: “Quentin Tarantino”, year: 1994 }],
[“The Shawshank Redemption”, { director: “Frank Darabont”, year: 1994 }]
]

Conclusion

In this post, we have learned how to sort a hash by value in Ruby using the sort_by method, both in ascending and descending order. We have also seen how to handle more complex data structures by modifying the block passed to the sort_by method. With this knowledge, you can now easily sort any hash by value in your Ruby projects.