在 Ruby 中将点符号键转换为树结构的 YAML

Convert dot notation keys to tree-structured YAML in Ruby

我已将我的 I18n 文件发送给第三方翻译。由于我的翻译不懂计算机,我们用键制作了一个电子表格,它们以点符号发送,并翻译了值。

例如:

es.models.parent: "Pariente"
es.models.teacher: "Profesor"
es.models.school: "Colegio"

如何将其移动到 YAML 文件中?

更新:正如@tadman 所说,这个已经是YAML。所以如果你和 在一起,你就好了。

因此,如果您想要 YAML 的树结构,我们将重点关注这个问题。

首先要做的是将其转换为哈希。

所以之前的信息移到了这里:

tr = {}
tr["es.models.parent"]  = "Pariente"
tr["es.models.teacher"] = "Profesor"
tr["es.models.school"]  = "Colegio"

然后我们继续创建更深的哈希。

result = {} #The resulting hash

tr.each do |k, value|
  h = result
  keys = k.split(".") # This key is a concatenation of keys
  keys.each_with_index do |key, index|
    h[key] = {} unless h.has_key? key
    if index == keys.length - 1 # If its the last element
      h[key] = value            # then we only need to set the value
    else
      h = h[key]
    end
  end
end;

require 'yaml'

puts result.to_yaml #Here it is for your YAMLing pleasure