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

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

问题描述

我在与Ruby混战,基本上我有

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

我想调用类似于 p>

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

访问

  trans [:links] [:quick_notes] 

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

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

sofar我想出了这种方法

pre $ $ $ $ c> def t(key)
a =''
key.to_s.split('。')。each {| key | a + =[:#{key}]}
#now a ==[:links] [:quick_notes]
#但我无法弄清楚如何在@trans变量上调用它

end

t('links.quick_notes')



任何想法? thanx

解决方案

您可以使用 注入

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

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

I'm fooling around with Ruby and basically I have

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

I want to call something like

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

to access

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

Any ideas ? thanx

解决方案

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