在 Ruby 中将点符号键转换为树结构的 YAML [英] Convert dot notation keys to tree-structured YAML in Ruby

查看:20
本文介绍了在 Ruby 中将点符号键转换为树结构的 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 I18n 文件发送给第三方进行翻译.由于我的翻译人员不精通计算机,因此我们制作了一个带有键的电子表格,它们以点表示法发送并翻译了值.

I've sent my I18n files to be translated by a third party. Since my translator is not computer savvy we made a spreadsheet with the keys, they where sent in dot notation and the values translated.

例如:

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

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

How can I move that into a YAML file?

更新:正如@tadman 所说,这已经是 YAML.所以,如果你在,你就好了.

UPDATE: Just like @tadman said, this already is YAML. So if you are with the, you are just fine.

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

So we will focus this question if you would like to have the tree structure for YAML.

推荐答案

首先要做的是将其转换为 Hash.

The first thing to do is transform this into a Hash.

所以以前的信息移动到这个:

So the previous info moved into this:

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

然后我们只是进一步创建了一个更深的哈希.

Then we just advanced creating a deeper hash.

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

这篇关于在 Ruby 中将点符号键转换为树结构的 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆