如何使用单个字符串键访问哈希的嵌套元素? [英] How do you access nested elements of a hash with a single string key?

查看:14
本文介绍了如何使用单个字符串键访问哈希的嵌套元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 Ruby,基本上我有

I'm fooling around with Ruby and basically I have

@trans = { :links => {
    :quick_notes => "aaaaaaa"
  }
}

我想调用类似

def t
  #...something
end
t('links.quick_notes')

访问

trans[:links][:quick_notes]

我基本上试图实现与使用国际化时相同的功能

I'm basically trying to achieve the same functionality like when using Internationalizations

I18n.t('something.other.foo') 

到目前为止我想出了这个方法

sofar I came up with this approach

 def t(key)
   a=''
   key.to_s.split('.').each{|key|  a+="[:#{key}]" } 
   #now a == "[:links][:quick_notes]"
   #but I cant figure out how can I call it on  @trans variable

 end

 t('links.quick_notes')

有什么想法吗?谢谢

推荐答案

您可以通过 到达那里注入:

You can get there with inject:

def t(key)
    key.to_s.split('.').inject(@trans) { |h, k| h[k.to_sym] }
end

错误检查和无此类条目"检查留作练习.

Error checking and "no such entry" checking is left as an exercise.

这篇关于如何使用单个字符串键访问哈希的嵌套元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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