按键数组设置红宝石哈希元素值 [英] set ruby hash element value by array of keys

查看:121
本文介绍了按键数组设置红宝石哈希元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我得到的:

  hash = {:a => {:b => [{:c => old_val}]}} 
keys = [:a,:b,0,:c]
new_val = 10

散列结构和密钥集可以不同。

i需要获得

  hash [:a] [:b] [0] [:c] == new_val 

谢谢!

/Enumerable.html#method-i-injectrel =noreferrer> 注入 来遍历嵌套结构:

  hash = {:a => {:b => [{:c => foo}]}} 
keys = [:a,:b,0,:c]

keys.inject(hash){| structure,key |结构[key]}
#=> foo

所以,你只需要修改它就可以对最后一个键进行设置。也许像

  last_key = keys.pop 
#=> :c

nested_hash = keys.inject(hash){| structure,key |结构[key]}
#=> {:c => foo}

nested_hash [last_key] =bar

hash
#=> {:a => {:b => [{:c => bar}]}}


here is what i got:

hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10

hash structure and set of keys can vary.
i need to get

hash[:a][:b][0][:c] == new_val

Thanks!

解决方案

You can use inject to traverse your nested structures:

hash = {:a => {:b => [{:c => "foo"}]}}
keys = [:a, :b, 0, :c]

keys.inject(hash) {|structure, key| structure[key]}
# => "foo"

So, you just need to modify this to do a set on the last key. Perhaps something like

last_key = keys.pop
# => :c

nested_hash = keys.inject(hash) {|structure, key| structure[key]}
# => {:c => "foo"}

nested_hash[last_key] = "bar"

hash
# => {:a => {:b => [{:c => "bar"}]}}

这篇关于按键数组设置红宝石哈希元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆