如何对 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屋!