Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/knut_tools/yaml.rb
Overview
Modify Hash, so to_yaml will output sorted by key
Instance Method Summary collapse
-
#to_yaml(emitter = {}) ⇒ Object
Unfortenatly the option :SortKeys => true isn’t supported in yaml-original.
Instance Method Details
#to_yaml(emitter = {}) ⇒ Object
Unfortenatly the option :SortKeys => true isn’t supported in yaml-original.
This extension adds this feature. Default is sorted, you may set it off.
If the keys may not be sorted “natural”, all keys are converted to Strings and the sorted. Mixtures of numbers and Strings will result in character sorted values (‘10’ will be before 2).
If the keys can’t be sorted (e.g. symbols…), the result keeps unsorted.
Source: groups.google.de/group/comp.lang.ruby/browse_thread/thread/813cd7086e37f004/3057ffb1ebd96a8d
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/knut_tools/yaml.rb', line 57 def to_yaml( emitter = {} ) =begin opt is a #<YAML::Syck::Emitter:0x2c182a0> I don't know how to get access to the ":SortKeys => true"-value correct. =end #~ opts = emitter #~ case emitter #~ when YAML::Syck::Emitter #~ opts = emitter.instance_variable_get('@options') #~ end YAML::quick_emit( object_id, emitter ) do |out| out.map( taguri, to_yaml_style ) do |map| #~ if opts[:SortKeys] ## fails in nesting, so let's just always sort sorted_keys = keys sorted_keys = begin sorted_keys.sort rescue sorted_keys.sort_by {|k| k.to_s} rescue sorted_keys end sorted_keys.each do |k| map.add( k, fetch(k) ) end #~ else #~ each do |k, v| #~ map.add( k, v ) #~ end #~ end end end end |