这是我得到的:
hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
哈希结构和密钥集可以有所不同 我需要得到
hash[:a][:b][0][:c] == new_val
谢谢!
答案 0 :(得分:6)
您可以使用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"}]}}
答案 1 :(得分:3)
与Andy相似,但您可以使用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