在for循环中将字符串转换为变量

时间:2011-09-13 20:04:45

标签: ruby

鉴于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

1 个答案:

答案 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。