鉴于RUBY中的以下代码,我需要遍历一堆哈希。问题是,varX是一个字符串,我需要它作为一个变量。有什么想法吗?
element1_old = {:ip => "192.168.0.191", :state => "PA", :county => "ambler"}
element1_new = {:ip => "192.168.0.191", :state => "PA", :county => "warrington"}
element2_old = {:ip => "192.168.0.192", :state => "PA", :county => "ambler"}
element2_new = {:ip => "192.168.0.192", :state => "PA", :county => "ambler"}
element3_old = {:ip => "192.168.0.200", :state => "PA", :county => "warrington"}
element3_new = {:ip => "192.168.0.200", :state => "PA", :county => "ambler"}
for i in 1..3
var1 = "element#{i}_old"
var2 = "element#{i}_new"
p element"#{i}".not_in_both("element#{i}_old")
end
答案 0 :(得分:0)
将哈希抛入另一个哈希:
h = {
'element1_old' => {:ip => "192.168.0.191", :state => "PA", :county => "ambler"},
'element1_new' => {:ip => "192.168.0.191", :state => "PA", :county => "warrington"},
'element2_old' => {:ip => "192.168.0.192", :state => "PA", :county => "ambler"},
'element2_new' => {:ip => "192.168.0.192", :state => "PA", :county => "ambler"},
'element3_old' => {:ip => "192.168.0.200", :state => "PA", :county => "warrington"},
'element3_new' => {:ip => "192.168.0.200", :state => "PA", :county => "ambler"}
}
for i in 1..3
old = h["element#{i}_old"]
new = h["element#{i}_new"]
p new.not_in_both(old)
end
我假设你的伪Ruby示例中element"#{i}"
实际上应该是element"#{i}"_new
,并且你已经将not_in_both
修补为Hash。