set ruby hash element value by array of keys

2019-07-09 05:14发布

问题:

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!

回答1:

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"}]}}


回答2:

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


标签: ruby hash