比较两个数组的散列,在ruby中没有任何特定的键



我想比较没有任何特定键"d"的所有值的2个哈希数组。请帮助比较两个数组的哈希,以一种迭代哈希数组中的所有值的方式。

A = [
{​​​​​​​​​​​"a"=>"1000", "b"=>"0", "c"=>"3", "d"=>"1", "e"=>"3", "f"=>"status"}​​​​​​​​​​​,

{​​​​​​​​​​​"a"=>"2", "e"=>"0", "b"=>"0", "c"=>"4", "d"=>"3", "e="3","f"=>"s-2"}​​​​​​​​​​​,

{​​​​​​​​​​​"a"=>"0", "b"=>"0", "c"=>"1", "d"=>"3", "e"=>"1", "f"=>"s-01"}​​​​​​​​​​ ]

B= [
{​​​​​​​​​​​"a"=>"1000", "b"=>"0", "c"=>"3", "d"=>"1", "e"=>"3", "f"=>"status"}​​​​​​​​​​​,

{​​​​​​​​​​​"a"=>"2", "e"=>"0", "b"=>"0", "c"=>"4", "d"=>"3", "e="3","f"=>"s-2"}​​​​​​​​​​​,

{​​​​​​​​​​​"a"=>"0", "b"=>"0", "c"=>"1", "d"=>"3", "e"=>"1", "f"=>"s-01"}​​​​​​​​​​ ]

我已经尝试了下面的代码,但我想比较没有特定键"d"的所有元素。请帮助!

A.each do |e_hash|  
B.each do |a_hash|
if (a_hash["d"].to_s == e_hash["d"].to_s)  
e_hash.each do |k,v|
puts v if k == "d"  if (a_hash[k].to_s != v.to_s)        
count += 1 
else     
count   
end     
end
end

当你想比较两个没有特定键的散列时,你可以使用

hash_1 = { "a" => 0, "b" => 0, "c" => 0 }
hash_2 = { "a" => 0, "b" => 0, "c" => 1 }
hash_1.tap { |hs| hs.delete("c") } == hash_2.tap { |hs| hs.delete("c") }
#=> true
在上面的例子中,你可以这样做:
A = [
{"a"=>"1000", "b"=>"0", "c"=>"3", "d"=>"1", "e"=>"3", "f"=>"status"},
{"a"=>"2", "e"=>"0", "b"=>"0", "c"=>"4", "d"=>"3", "e"=>"3", "f"=>"s-2"},
{"a"=>"0", "b"=>"0", "c"=>"1", "d"=>"3", "e"=>"1", "f"=>"s-01"} 
]
B = [
{"a"=>"1000", "b"=>"0", "c"=>"3", "d"=>"1", "e"=>"3", "f"=>"status"},
{"a"=>"2", "e"=>"0", "b"=>"0", "c"=>"4", "d"=>"3", "e"=>"3", "f"=>"s-2"},
{"a"=>"0", "b"=>"0", "c"=>"1", "d"=>"3", "e"=>"1", "f"=>"s-01"} 
]
A.each do |e_hash|  
B.each do |a_hash|
if e_hash.tap { |hs| hs.delete("d") } == a_hash.tap { |hs| hs.delete("d") }
puts "Equal hash found: #{e_hash}"
end
end     
end
#=> Equal hash found: {"a"=>"1000", "b"=>"0", "c"=>"3", "e"=>"3", "f"=>"status"}
#   Equal hash found: {"a"=>"2", "e"=>"3", "b"=>"0", "c"=>"4", "f"=>"s-2"}
#   Equal hash found: {"a"=>"0", "b"=>"0", "c"=>"1", "e"=>"1", "f"=>"s-01"}

相关内容

最新更新