Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

ruby - How do you access nested elements of a hash with a single string key?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...