我正在檢查下面的哈希hash_volumes
是否有一個密鑰,其instance_id
與哈希hash_instance
的密鑰匹配。將特定值上的兩個哈希合併
hash_volumes = {
:"vol-d16d12b8" => {
:instance_id => "i-4e4ba679",
},
}
hash_instance = {
:"i-4e4ba679" => {
:arch => "x86_64",
},
}
如果是這樣的話,我需要將其合併到hash_instance
。我發現,vol-d16d12b8
與實例i-4e4ba679
比賽,所以我想與hash_instance
進行合併,以便最終hash_instance
看起來象下面這樣:
hash_instance = {
:"i-4e4ba679" => {
:arch => "x86_64",
:volume => "vol-d16d12b8" # this is new entry to `hash_instance`
},
}
我不能如上所述這兩個散列合併。我懷疑我的if
聲明是錯誤的。請大家看看下面我的代碼:
hash_volumes.each_key do |x|
hash_instance.each_key do |y|
if hash_volumes[x][:instance_id] == y ## I think this line is the problem
hash_instance[y][:volume] = x
end
end
end
hash_instance
輸出:
{
:"i-4e4ba679" => {
:arch => "x86_64"
}
}
上面的代碼給hash_instance
無添加volume
它。我嘗試如下,但沒有工作:
if hash_volumes[x][:instance_id] == "#{y}"
# => this if statement gives me syntax error
.....
if hash_volumes[x][:instance_id] =~ /"#{y}"/
# => this if statement does not make any changes to above output.
@sawa,感謝點出來。我編輯了代碼。在編寫測試代碼以便在SO上發佈時,我總是犯錯。 – slayedbylucifer
好。現在我將刪除重複以使您的問題簡潔。 – sawa
@sawa,謝謝.. – slayedbylucifer