Never been to DZone Snippets before?

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

About this user

Dov Murik

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Generating YAML hashes sorted by key

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:

   1  
   2  require 'yaml'
   3   
   4  class Hash
   5    # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys)
   6    #
   7    # Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb
   8    def to_yaml( opts = {} )
   9      YAML::quick_emit( object_id, opts ) do |out|
  10        out.map( taguri, to_yaml_style ) do |map|
  11          sort.each do |k, v|   # <-- here's my addition (the 'sort')
  12            map.add( k, v )
  13          end
  14        end
  15      end
  16    end
  17  end


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

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


will always output this:

   1  
   2  ---
   3  aaa: should be first
   4  bbb: near beginning
   5  mmm: middle
   6  zzz: I'm last
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS