当您只关心相交键时,如何在 Ruby 中轻松测试哈希相等性?

发布于 2024-08-10 19:37:57 字数 593 浏览 3 评论 0原文

假设我有以下哈希:

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

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

在此示例中,“b”键是两个哈希值之间唯一的共同点,并且它的值在两个哈希值中都设置为“2”,因此按照该逻辑,这两个哈希值将被视为相等。

同样,由于“d”键不相等,这两个哈希值不会相等(“a”和“c”键值被忽略,因为它们对于各自的哈希值来说是唯一的):

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

Ruby 中是否有一个聪明的单行代码可以计算两个哈希的相交键,然后根据这些键比较它们的值是否相等?

如果您提供测试,则会获得奖励积分。

如果您将其猴子修补到 Hash 类中,则会获得更多奖励积分。

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.

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):

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?

Bonus points if you provide tests.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-柠檬树下少年和吉他 2024-08-17 19:37:57
def compare_intersecting_keys(a, b)
  (a.keys & b.keys).all? {|k| a[k] == b[k]}
end

像这样使用:

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

如果你想要它猴子补丁:

class Hash
  def compare_intersection(other)
    (self.keys & other.keys).all? {|k| self[k] == other[k]}
  end
end
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文