【问题标题】:Convert dot notation keys to tree-structured YAML in Ruby在 Ruby 中将点符号键转换为树结构的 YAML
【发布时间】:2016-10-20 19:55:11
【问题描述】:

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

例如:

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

如何将它移到 YAML 文件中?

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

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

【问题讨论】:

  • 那是 YAML,所以没有太多工作要做。
  • 你是绝对正确的。我以前从未见过这种格式,更习惯于树状结构。

标签: ruby yaml rails-i18n


【解决方案1】:

首先要做的就是把它转换成一个哈希。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2013-03-30
    • 2020-09-23
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多