6

I'm trying to get a general solution to the problem of accessing an element in a nested hash given an array of key values,e.g.:

hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

function(array)
=> "foo"

I'm guessing this could be a one-liner. It also is quite closely related to this problem: Ruby convert array to nested hash

2
  • I did not spot that - whoops Commented Aug 15, 2013 at 11:16
  • The link you have given.. is awesome..I learnt a new concept from that..thanks for finding it out... :) Commented Aug 15, 2013 at 11:19

1 Answer 1

13
hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! In case it helps anyone else, I came across this answer while looking for a Ruby equivalent to Clojure's get-in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.