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

Community
  • 1
  • 1
waferthin
  • 1,582
  • 1
  • 16
  • 27

1 Answers1

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

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Thanks! In case it helps anyone else, I came across this answer while looking for a Ruby equivalent to Clojure's `get-in`. – pdoherty926 Nov 15 '17 at 19:43