Forum: Ruby Yaml & SortKeys in 1.8.4

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ron M (Guest)
on 2006-02-20 22:58
(Received via mailing list)
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
Joel VanderWerf (Guest)
on 2006-02-20 23:23
(Received via mailing list)
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
This topic is locked and can not be replied to.