Ticket #3 (assigned enhancement)

Opened 3 years ago

Last modified 20 months ago

bring back sorted hash keys

Reported by: vjoel@… Owned by: why
Priority: major Milestone: milestone1
Component: component2 Version:
Keywords: to_yaml sort sortkeys hash Cc:

Description

After upgrading from ruby-1.8.2 to ruby-1.8.4, the readability of my yaml files decreased due #to_yaml ignoring :SortKeys?.

irb(main):006:0> puts h.to_yaml
---
5: 5
1: 1
2: 2
3: 3
4: 4
=> nil
irb(main):007:0> h
=> {5=>5, 1=>1, 2=>2, 3=>3, 4=>4}
irb(main):008:0> puts h.to_yaml(:SortKeys=>true)
---
5: 5
1: 1
2: 2
3: 3
4: 4
=> nil

I suggest that sorting keys should either be automatic or optional.

Change History

  Changed 3 years ago by anonymous

+1 for sorted keys

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.

  Changed 3 years ago by anonymous

A workaround Joel VanderWerf? posted to ruby-talk was very useful to me:

(sorry, don't know how to link to a ruby-talk email, so plagerising his code here)

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

  Changed 2 years ago by why

  • owner changed from somebody to why
  • status changed from new to assigned
  • milestone set to milestone1

All the options stuff (:SortKeys?, :UseHeader?) was moved into emitter.c when 0.60 came out. But, yes, I need to add accessors for each of them.

in reply to: ↑ description   Changed 20 months ago by ahoward

absolutely - this is important to people. can i help?

Note: See TracTickets for help on using tickets.