How can I sort YAML files?

前端 未结 9 964
灰色年华
灰色年华 2021-02-02 12:55

I\'ve been trying to sort an i18n translations YAML file with Ruby so I can manage new translations in a better and organized way, but I\'ve been wondering if there is something

9条回答
  •  暖寄归人
    2021-02-02 13:00

    In Ruby 1.8 hashes don't have a particular order, so you cannot just sort them.

    You could monkey-patch/overwrite the to_yaml method of Hash like this:

    #!/usr/local/bin/ruby -w
    
    require 'yaml'
    
    class Hash
      def to_yaml(opts = {})
        YAML::quick_emit(self, opts) do |out|
          out.map(taguri, to_yaml_style) do |map|
            keys.sort.each do |k|
              v = self[k]
              map.add(k, v)
            end
          end
        end
      end
    end
    
    dict = YAML.load($<.read)
    
    puts dict.to_yaml
    

    Of course, the exact details may depend on your version of YAML/Ruby. The example above is for Ruby 1.8.6.

提交回复
热议问题