How can I sort YAML files?

前端 未结 9 963
灰色年华
灰色年华 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 12:57

    In my use cases where deep sorting a hash is needed, the hash is always a tree where keys are labels and values are (sub)trees (if hashes) or leaves (otherwise). I need to deep-sort only the labels of trees (not the values).

    I got this

    before: {"a":[2,10,{"5":null,"1":null,"3":null}],"x":{"5":null,"1":null,"3":null},"a2":{"5":[2,10,5],"1":null,"3":null}}
    after:  {"a":[2,10,{"5":null,"1":null,"3":null}],"a2":{"1":null,"3":null,"5":[2,10,5]},"x":{"1":null,"3":null,"5":null}}
    

    with this

        def deeply_sort_hash(object)
          return object unless object.is_a?(Hash)
          hash = Hash.new
          object.each { |k, v| hash[k] = deeply_sort_hash(v) }
          sorted = hash.sort { |a, b| a[0].to_s <=> b[0].to_s }
          hash.class[sorted]
        end
    

提交回复
热议问题