Sorting a Hash Recursively with Ruby

Featured image for sharing metadata for article

As part of Diffing Pretty-Printed JSON Files, I wanted to have a method of making JSON documents easier to diff by sorting their keys.

I wanted to use this solution by Brian Dunagan, but it didn't seem to quite work when, in my example, I had an Arrays which may have Hashes but may also not.

My amended solution is:

def recursive_sort(v, &block)
  if v.class == Hash
    v.sorted_hash(&block)
  elsif v.class == Array
    v.collect {|a| recursive_sort(a, &block)}
  else
    v
  end
end

class Hash
  def sorted_hash(&block)
    self.class[
      self.each do |k,v|
        self[k] = recursive_sort(v, &block)
      end.sort(&block)]
  end
end

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.