2

这是我得到的:

hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10

散列结构和键集可能会有所不同。
我需要得到

hash[:a][:b][0][:c] == new_val

谢谢!

4

2 回答 2

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"}]}}
于 2012-12-13T09:30:58.517 回答
3

类似于安迪的,但你可以用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
于 2012-12-13T09:43:16.573 回答