DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Generating YAML Hashes Sorted By Key

07.23.2008
| 9591 views |
  • submit to reddit
        I needed to store YAML structures in version control, so I wanted the YAML output of hashes to be sorted by the key name (this way, when using "diff" between two versions, you'll get a minimal changeset).

Of course a Hash object in Ruby doesn't have any ordering on its keys, which is fine. I just want to make sure that when I output the YAML serialization of a Hash object, it will serialize the keys in alphabetic order.

Put this code somewhere before you actually serialize your hashes:

require 'yaml'
 
class Hash
  # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys)
  #
  # Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb
  def to_yaml( opts = {} )
    YAML::quick_emit( object_id, opts ) do |out|
      out.map( taguri, to_yaml_style ) do |map|
        sort.each do |k, v|   # <-- here's my addition (the 'sort')
          map.add( k, v )
        end
      end
    end
  end
end

Now simply use "to_yaml" or "y" on your hash object. For example, this code:

my_hash = { "aaa" => "should be first", "zzz" => "I'm last", "mmm" => "middle", "bbb" => "near beginning" }
puts my_hash.to_yaml

will always output this:

---
aaa: should be first
bbb: near beginning
mmm: middle
zzz: I'm last