Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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

like image 858
equivalent8 Avatar asked Jul 12 '11 22:07

equivalent8


1 Answers

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.

like image 67
mu is too short Avatar answered Oct 21 '22 11:10

mu is too short