hash - Compare two complex hashes in ruby -
i'm trying compare 2 hashes recursively in ruby, there caveats. can't compare strings because 1 hash uses nil , 1 uses 0 etc
here function:
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) , f.include?(yaml2)) or (t.include?(yaml1) , t.include?(yaml2)) return true end if (nil_equivalents.include?(yaml1) && nil_equivalents.include?(yaml2)) # puts "we found nil" return true end if (yaml1.class == yaml2.class) if yaml1.class.to_s == "hash" puts "gotta hash" + yaml1.to_s # = 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
i try test if following line:
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]]}}})
which should return true, not
can help?
your sample should return false because:
"x86 family 6 model 14 stepping 8 " != "x86 family 6 model 14 stepping 8"
(there space @ end of first)"x86 family 15 model 4 stepping 1 " != "x86 family 15 model 4 stepping 1"
(same thing){"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]]}}
(the first 1 missing "windows xp pro")"hewlett packard" != "hewlett-packard"
and on , on...
bottom line - sample should not return true...
Comments
Post a Comment