Last Updated: February 25, 2016
·
1.076K
· destructuring

Sort a Ruby hash for comparison

I compare Ruby hashes by sorting the keys and emitting yaml into diff, vimdiff. Useful for comparing chef dna, for example.

A simple monkey patch of Hash:

class Hash
  alias hkeys keys

  def keys
    hkeys.sort {|a,b| a.to_s <=> b.to_s }

  def each
    keys.each { |k| yield k, self[k] }
  end
end

Then for anything that can become a hash:

puts anything.to_hash.to_yaml