使用虚线路径密钥字符串访问Ruby哈希 [英] Access Ruby Hash Using Dotted Path Key String

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

问题描述

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

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

有谁知道如何用Ruby哈希做到这一点?或者只能直接通过YAML对象?

解决方案

只需在路径中的一个点上分割并遍历它就可以找到正确的散列?

  path.split(。)。inject(hash){| hash,key |另外,你可以通过在整个结构上迭代迭代来构建一个新的散列: >  


$ b


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

如果v.is_a?哈希
ret.merge! convert_hash(v,key +。)
else
ret [key] = v
end
end
end


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')

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天全站免登陆