Convert string into variable within for loop
Given the following code in RUBY, I need to loop through a bunch of hashes. The problem is, varX is a string, I need it to be a variable. Any ideas?
element1_old = {:ip => "192.168.0.191", :state => "PA", :county => "ambler"}
element1_new = {:ip => "192.168.0.191", :state => "PA", :county => "warrington"}
el开发者_高级运维ement2_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
Throw the hashes into another hash:
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
I'm assuming that element"#{i}"
is actually supposed to be element"#{i}"_new
in your pseudo-Ruby example and that you have monkey patched not_in_both
into Hash.
精彩评论