使用点分路径键字符串访问 Ruby 哈希 [英] Access Ruby Hash Using Dotted Path Key String

查看:13
本文介绍了使用点分路径键字符串访问 Ruby 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails I18n 库将 YAML 文件转换为可使用 t() 函数通过虚线路径调用访问的数据结构.

The Rails I18n library transforms a YAML file into a data structure that is accessible via a dotted path call using the t() function.

t('one.two.three.four')

有谁知道如何使用 Ruby 哈希来做到这一点?还是只能通过 YAML 对象直接实现?

Does anyone know how to do this with a Ruby Hash? Or is it only possible directly via a YAML object?

推荐答案

只需在路径中的一个点上分割并遍历它以找到正确的哈希?

Just split on a dot in the path and iterate over this to find the right hash?

path.split(".").inject(hash) { |hash, key| hash[key] }

或者,您可以通过在整个结构上递归迭代来构建一个新的哈希:

Alternatively you can build a new hash by iterating recursively over the whole structure:

def convert_hash(hash, path = "")
  hash.each_with_object({}) do |(k, v), ret|
    key = path + k

    if v.is_a? Hash
      ret.merge! convert_hash(v, key + ".")
    else
      ret[key] = v
    end
  end
end

这篇关于使用点分路径键字符串访问 Ruby 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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