通过按键的数组指定访问嵌套的散列元素 [英] Access nested hash element specified by an array of keys
本文介绍了通过按键的数组指定访问嵌套的散列元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图去给出键值数组的嵌套哈希,例如访问一个元素的问题的通用解决方案:
散= {A=> {B=> '富'}}
数组= [一,B]功能(阵列)
= GT; 富
我猜这可能是一个班轮。它也相当密切的关系,这一问题:
红宝石转换阵列嵌套哈希
解决方案
散= {A=> {B=> '富'}}
数组= [一,B]array.inject(哈希:取)
#=> 富
array.inject(哈希:[])
#=> 富
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
解决方案
hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]
array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"
这篇关于通过按键的数组指定访问嵌套的散列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文