通过键数组设置ruby哈希元素值

Iva*_*ets 2 ruby hash

这是我得到的:

hash = {:a => {:b => [{:c => old_val}]}}
keys = [:a, :b, 0, :c]
new_val = 10
Run Code Online (Sandbox Code Playgroud)

哈希结构和密钥集可以变化.
我需要得到

hash[:a][:b][0][:c] == new_val
Run Code Online (Sandbox Code Playgroud)

谢谢!

And*_*nes 6

您可以使用inject遍历嵌套结构:

hash = {:a => {:b => [{:c => "foo"}]}}
keys = [:a, :b, 0, :c]

keys.inject(hash) {|structure, key| structure[key]}
# => "foo"
Run Code Online (Sandbox Code Playgroud)

所以,你只需要修改它就可以在最后一个键上进行设置.也许是这样的

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"}]}}
Run Code Online (Sandbox Code Playgroud)