set ruby hash element value by array of keys

2019-07-09 05:08发布

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!

标签: ruby hash
2条回答
Lonely孤独者°
2楼-- · 2019-07-09 05:59

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"}]}}
查看更多
Emotional °昔
3楼-- · 2019-07-09 06:08

Similar to Andy's, but you can use Symbol#to_proc to shorten it.

hash = {:a => {:b => [{:c => :old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
keys[0...-1].inject(hash, &:fetch)[keys.last] = new_val
查看更多
登录 后发表回答