如何排序YAML文件? [英] How can I sort YAML files?
问题描述
我一直在尝试使用Ruby对i18n翻译YAML文件进行排序,以便我可以更好地组织井井有条的新翻译,但是我一直在想是否有一些方法可以简化任务.
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 to ease the task.
我找到了一个YAML文件编写器,因此可以将哈希写入文件中,但是我的问题是正确对哈希进行排序.如果我得到哈希h
,则h.sort
返回一个数组,但我仍然没有找到简单的方法.
I found a YAML file writer so I can write a hash into a file, but my problem is to sort the hash correctly. If I got hash h
, h.sort
returns an array and I still haven't figured a simple way to do that.
我有这样的YAML文件:
I have YAML files like this:
pt-br:
global:
misc:
total: "Total"
all: "Todos"
close: "Fechar"
cancel: "Cancelar"
crud:
access: "Acessar"
back: "Voltar"
edit: "Editar"
confirm: "Confirmar"
send: "Enviar"
...
(文件比这大得多)
但是我想用这种方式对它们进行排序:
But I want to sort them this way:
pt-br:
global:
crud:
access: "Acessar"
back: "Voltar"
confirm: "Confirmar"
edit: "Editar"
send: "Enviar"
misc:
all: "Todos"
cancel: "Cancelar"
close: "Fechar"
total: "Total"
我认为一些简单的递归方法可以帮助我:
I thought that some simple recursive method could help me like this:
def translation_sort(h)
if h.class == Hash
h = h.sort
h.each{|item| translation_sort(item)}
end
h
end
require "yaml"
h=YAML.load_file(File.open("~/pt-br.sample.yml"))
translation_sort(h)
推荐答案
实际上,这是一个很好的问题.您想对哈希进行深层排序.因此,我不想重新发明轮子,然后我寻找了一个好的实现,然后找到了我喜欢的实现.看看 https://gist.github.com/1083930 .它工作正常.
Actually this is a nice question. You want to deep sort hashes. So I don't like to re-invent the wheel and then I searched for a good implementation and I found one I like. Take a look at it https://gist.github.com/1083930. It works fine.
这篇关于如何排序YAML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!