我试图在ruby中递归地比较两个哈希,但是有一些警告。我不能简单地比较字符串,因为一个哈希使用nil而一个使用0等
这是我的功能:
def compare_yaml(yaml1,yaml2)
f = ["f", "false", false]
t = ["t", "true", true]
nil_equivalents = [0, "", [], {}, nil, " "]
return true if yaml1 == yaml2
if (f.include?(yaml1) and f.include?(yaml2)) or (t.include?(yaml1) and t.include?(yaml2))
return true
end
if (nil_equivalents.include?(yaml1) && nil_equivalents.include?(yaml2)) then
# puts "we found a nil"
return true
end
if (yaml1.class == yaml2.class)
if yaml1.class.to_s == "Hash"
puts "gotta hash" + yaml1.to_s
# a = yaml1.inspect
# b = yaml2.inspect
yaml1.keys.map{|k| (yaml2.keys.include? k)? compare_yaml(yaml1[k], yaml2[k]) : false}.reduce{|n,m| n&&m}
end
if yaml1.class.to_s == "Array"
return false unless yaml1.length == yaml2.length
# yaml1.sort!
# yaml2.sort!
return yaml1.zip(yaml2).map { |e| compare_yaml(e[0],e[1])}.reduce{|n,m| n&&m}
end
end
return false
end
我尝试使用以下行测试:
compare_yaml({"Computer"=>{"Axiom Tech Co"=>{"Windows 2003"=>[["x86 Family 6 Model 14 Stepping 8 ", nil, 1]]}, "Dell"=>{"Windows 2003"=>[["x86 Family 15 Model 4 Stepping 1 ", nil, 1]]}}, "Desktop"=>{"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}, "Laptop"=>{"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}},{"Computer"=>{"Axiom Tech Co"=>{"Windows 2003"=>[["x86 Family 6 Model 14 Stepping 8", 0, 1]]}, "Dell"=>{"Windows 2003"=>[["x86 Family 15 Model 4 Stepping 1", 0, 1]]}}, "Desktop"=>{"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}, "Laptop"=>{"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}})
应返回true,但不是
有人可以帮忙吗?
答案 0 :(得分:0)
您的样本应该返回false,因为:
"x86 Family 6 Model 14 Stepping 8 " != "x86 Family 6 Model 14 Stepping 8"
(第一个末尾有一个空格)"x86 Family 15 Model 4 Stepping 1 " != "x86 Family 15 Model 4 Stepping 1"
(同样的事){"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}} != {"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}
(第一个缺失" Windows XP专业版")"Hewlett Packard" != "Hewlett-Packard"
等等...
底线 - 您的样本应该不返回true ...