
Deeply Sort Nested Ruby Arrays and Hashes
Mark Crossen
Reading time: about 2 min
Topics:
If you’ve ever scripted in Ruby before, you’ve more than likely encountered deeply nested arrays and hashes. These nested structures often come from Ruby’s JSON parser, but Ruby itself doesn’t have effective methods for dealing with them. Specifically, sorting these structures: the standard routine only shallow sorts the top layer instead of deeply sorting every nested array and hash that the structure contains. This issue became apparent in Cumulus—an open source project sponsored by Lucid Software. After being unable to find an adequate solution, a simple utility was made that deeply sorts nested structures. Although small, the utility was incredibly useful—so it was made into a standalone Ruby Gem.
[
{
"name": "Steve",
"relatives": [
"Ray",
"Mark",
"Jeff",
"David"
]
},
{
"relatives": [
"Mary",
"Joe",
"Harry"
],
"name": "John"
}
]
require “deepsort”
require “json”
result = JSON.parse(File.read("nasty.json")).deep_sort
puts JSON.pretty_generate(result)
[
{
"name": "John",
"relatives": [
"Harry",
"Joe",
"Mary"
]
},
{
"name": "Steve",
"relatives": [
"David",
"Jeff",
"Mark",
"Ray"
]
}
]
But wait—the goodness doesn't stop there! The gem also includes in-place and configurable methods such as deep_sort!, deep_sort_by, and deep_sort_by!, similar to ruby's built-in sort!, sort_by, and sort_by!
gem install deepsort
The deepsort gem is Open Source (MIT license). Feel free to contribute, comment, or learn more on the project's GitHub page.
About Lucid
Lucid Software is the leader in visual collaboration and work acceleration, helping teams see and build the future by turning ideas into reality. Its products include the Lucid Visual Collaboration Suite (Lucidchart and Lucidspark) and airfocus. The Lucid Visual Collaboration Suite, combined with powerful accelerators for business agility, cloud, and process transformation, empowers organizations to streamline work, foster alignment, and drive business transformation at scale. airfocus, an AI-powered product management and roadmapping platform, extends these capabilities by helping teams prioritize work, define product strategy, and align execution with business goals. The most used work acceleration platform by the Fortune 500, Lucid's solutions are trusted by more than 100 million users across enterprises worldwide, including Google, GE, and NBC Universal. Lucid partners with leaders such as Google, Atlassian, and Microsoft, and has received numerous awards for its products, growth, and workplace culture.