2012-12-13 60 views
1

的陣列組紅寶石哈希元素值是我得到:通過鍵

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

散列結構和設置鍵可以變化的。
我需要得到

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

謝謝!

回答

4

您可以使用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"}]}} 
+0

謝謝。最後以'd = b.pop'' b.inject(a){| s,k | s [k]} [d] = 20' –

2

與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 
+0

不錯!我之前從未使用過'fetch',所以我沒有想到它! –