Access nested hash element specified by an array o

2019-05-03 15:03发布

问题:

This question already has an answer here:

  • ruby use array tvalues to index nested hash of hash [duplicate] 4 answers
  • Map array of ints to nested array access 2 answers

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

回答1:

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

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"


标签: ruby arrays hash