Access nested hash element specified by an array o

2019-05-03 14:38发布

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

标签: ruby arrays hash
1条回答
男人必须洒脱
2楼-- · 2019-05-03 15:31
hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"
查看更多
登录 后发表回答