Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

visiting hash with keys from array

I have a big hash with lots of nested key value pairs. Eg.

h = {"foo" => {"bar" => {"hello" => {"world" => "result" } } } }

Now I want to access result and I have keys for that in array in proper sequence.

keys_arr = ["foo", "bar", "hello", "world"]

The motive is clear, I want to do following:

h["foo"]["bar"]["hello"]["world"]
# => "result"

But I don't know how to do this. I am currently doing:

key = '["' +  keys_arr.join('"]["') + '"]'
eval("h"+key)
# => "result"

Which looks like a hack. Also it greatly reduces my ability to work with hash in real environment.

Please suggest alternate and better ways.

like image 417
shivam Avatar asked May 15 '26 17:05

shivam


2 Answers

Using Enumerable#inject (or Enumerable#reduce):

h = {"foo" => {"bar" => {"hello" => {"world" => "result" } } } }
keys_arr = ["foo", "bar", "hello", "world"]
keys_arr.inject(h) { |x, k| x[k] }
# => "result"

UPDATE

If you want to do something like: h["foo"]["bar"]["hello"]["world"] = "ruby"

innermost = keys_arr[0...-1].inject(h) { |x, k| x[k] } # the innermost hash
innermost[keys_arr[-1]] = "ruby"
like image 112
falsetru Avatar answered May 17 '26 07:05

falsetru


keys_arr.inject(h, :[])

will do

like image 45
sawa Avatar answered May 17 '26 07:05

sawa