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"}]}}
d=b.pop b.inject(a) {|s,k| s[k]}[d] = 20Similar 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
fetch on an array before, so I didn't think of it!