Yaml & SortKeys in 1.8.4


#1

IIRC, in a previous version, I was able to make more
human-friendly YAML using the :SortKeys option as shown below.

Since upgrading to 1.8.4 the keys seem not to be sorted anymore.
Has the way of doing this changed? I hope this feature hasn’t
gone away. The main reason we’re using YAML instead of XML is
that it was more human-readable, and the SortKeys option added
a major part of the human-readability.

irb(main):016:0> puts(
{1,‘a’,2,‘b’,3,‘c’,4,‘d’,5,‘d’}.to_yaml(:Indent=>1,:SortKeys=>true))

5: d
1: a
2: b
3: c
4: d
=> nil


#2

Ron M wrote:

irb(main):016:0> puts(
{1,‘a’,2,‘b’,3,‘c’,4,‘d’,5,‘d’}.to_yaml(:Indent=>1,:SortKeys=>true))

5: d
1: a
2: b
3: c
4: d
=> nil

It grieves me also. I submitted a request to:

http://code.whytheluckystiff.net/syck/ticket/3

In the interim, you can load the following patch whenever you want to
get sorted hash keys (for all hashes, unfortunately).

class Hash
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
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
  end
end

end
end