这是我得到的:
hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
散列结构和键集可能会有所不同。
我需要得到
hash[:a][:b][0][:c] == new_val
谢谢!
您可以使用inject
遍历嵌套结构:
hash = {:a => {:b => [{:c => "foo"}]}}
keys = [:a, :b, 0, :c]
keys.inject(hash) {|structure, key| structure[key]}
# => "foo"
因此,您只需要修改它以对最后一个键进行设置。也许像
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"}]}}
类似于安迪的,但你可以用Symbol#to_proc
它来缩短它。
hash = {:a => {:b => [{:c => :old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
keys[0...-1].inject(hash, &:fetch)[keys.last] = new_val