当您只关心交叉键时,如何轻松地测试Ruby中的散列等式?

时间:2021-04-07 16:20:55

Say I have the following hashes:

假设我有以下散列:

hash_x = {
  :a => 1,
  :b => 2
}
hash_y = {
  :b => 2,
  :c => 3
}

I need a chunk of logic that compares the two for equality only taking into consideration intersecting keys.

我需要一大块逻辑来比较两者的相等性,只考虑相交的键。

In this example the 'b' key is the only commonality between the two hashes and it's value is set to '2' in both so by that logic these two hashes would be considered equal.

在这个例子中,“b”键是这两个散列之间唯一的公共性,它的值在两个散列中都被设置为“2”,因此根据这个逻辑,这两个散列将被认为是相等的。

Likewise these two hashes would not be equal due to the inequality of the 'd' key (the 'a' and 'c' key values are ignored since they are unique to their respective hashes):

同样,由于‘d’键的不平等(‘a’和‘c’键值被忽略,因为它们是各自的哈希唯一的值),这两个哈希值也不相等:

hash_p = {
  :a => 1,
  :b => 2,
  :d => 3,
}
hash_q = {
  :b => 2,
  :c => 3,
  :d => 4
}

Is there a clever one-liner in Ruby that can calculate the intersecting keys of the two hashes then compare their values for equality based on those keys?

Ruby中是否有一种聪明的一行程序,它可以计算两个散列的相交键,然后根据这些键比较它们的值,使它们相等?

Bonus points if you provide tests.

如果你提供测试,奖励积分。

More bonus points if you monkey-patch it into the Hash class.

如果您将其添加到散列类中,则会获得更多的额外加分。

1 个解决方案

#1


9  

def compare_intersecting_keys(a, b)
  (a.keys & b.keys).all? {|k| a[k] == b[k]}
end

Use like this:

使用这样的:

compare_intersecting_keys(hash_x, hash_y)  # => true
compare_intersecting_keys(hash_p, hash_q)  # => false

If you want it monkey-patched:

如果你想要修补的话:

class Hash
  def compare_intersection(other)
    (self.keys & other.keys).all? {|k| self[k] == other[k]}
  end
end

#1


9  

def compare_intersecting_keys(a, b)
  (a.keys & b.keys).all? {|k| a[k] == b[k]}
end

Use like this:

使用这样的:

compare_intersecting_keys(hash_x, hash_y)  # => true
compare_intersecting_keys(hash_p, hash_q)  # => false

If you want it monkey-patched:

如果你想要修补的话:

class Hash
  def compare_intersection(other)
    (self.keys & other.keys).all? {|k| self[k] == other[k]}
  end
end