如何比较两个填充哈希的数组并返回第二个不存在的哈希?

时间:2014-09-01 12:12:18

标签: ruby arrays hash compare

假设我有两个充满哈希的数组,

array_a = [{'key' => 'a'}, {'key' => 'b'}, {'key' => 'c'}, {'key' => 'd'}]
array_b = [{'key' => 'a'}, {'key' => 'b'}, {'key' => 'd'}]

如何比较array_aarray_b并返回array_b中未找到的哈希值。

所以比较应该返回:

# => [{'key' => 'c'}]

1 个答案:

答案 0 :(得分:6)

Array#-可行:

array_a = [{'key' => 'a'}, {'key' => 'b'}, {'key' => 'c'}, {'key' => 'd'}]
array_b = [{'key' => 'a'}, {'key' => 'b'}, {'key' => 'd'}]

array_a - array_b
#=> [{"key"=>"c"}]

方法" ...使用hasheql?方法..." 并根据Hash#hash比较元素:

  

具有相同内容的两个哈希将具有相同的哈希码(并将使用eql?进行比较)。