当您只关心相交键时,如何在 Ruby 中轻松测试哈希相等性?
假设我有以下哈希:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样使用:
如果你想要它猴子补丁:
Use like this:
If you want it monkey-patched: