【发布时间】:2021-11-15 16:04:10
【问题描述】:
假设我有 3 个哈希
hash1 = {'a' => 1, 'b' => 2}
hash2 = {'a' => 1, 'b' => 2, 'd' => 3}
hash3 = {'a' => 1, 'b' => 2, 'c' => 4, 'd' => 3}
hash4 = {'c' => 4, 'd' => 3, 'e' = 5}
预期结果
hash1 == hash2 # => true
hash1 == hash3 # => true
hash1 == hash4 # => false (has no common keys to compare their values)
hash2 == hash3 # => true
所以基本上我想在比较时比较两个哈希中相同键的值。如果没有公共键,则返回 false
编辑: @CarySwoveland 的提示,他的解决方案非常有效:
common_keys = hash1.keys & hash2.keys;
if common_keys.any?
hash1.values_at(*common_keys) == hash2.values_at(*common_keys);
else
false
end
【问题讨论】:
-
你需要一个方法,例如
test(hash1, hash2)或覆盖==? -
@razvans 最好有一个方法,而不是猴子补丁
-
试试这个:
common_keys = hash1.keys & hash2.keys; hash1.values_at(*common_keys) == hash2.values_at(*common_keys). -
@CarySwoveland 这取决于任何特定的顺序?
-
@Danyil - 未成年人,但你可以写
common_keys.any? && hash1.values_at(*common_keys) == [...]
标签: ruby-on-rails ruby hash