Skip to content

Instantly share code, notes, and snippets.

@djsun
Created January 29, 2010 15:37
Show Gist options
  • Save djsun/289815 to your computer and use it in GitHub Desktop.
Save djsun/289815 to your computer and use it in GitHub Desktop.
sorted_yaml_hash.rb
# Based on http://snippets.dzone.com/posts/show/5811
#
# Differences over snippet above:
# * will sort hashes with keys that are symbols
# * different usage style (see below)
require 'yaml'
module SortedYamlHash
def to_yaml(opts = {})
YAML::quick_emit(object_id, opts) do |out|
out.map(taguri, to_yaml_style) do |map|
self.sort { |a, b| a.to_s <=> b.to_s }.each do |k, v|
v.extend(SortedYamlHash) if v.is_a?(Hash)
map.add(k, v)
end
end
end
end
end
h = {
:a => {
'dog' => 2,
'zebra' => 4,
'camel' => 10,
},
:b => {
:z => 'z',
:y => 'y',
:x => 'x',
}
}.extend(SortedYaml)
y h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment