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
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