假設我有3個哈希值
hash1 = {'a' => 1, 'b' => 2}.
hash2 = {'a' => 1, 'b' => 2, 'd' => 3} hash3 = {, 'd' => 3 }
hash3 = {'a' => 1, 'b' => 2, 'c' => 4, 'd' => 3}hash4 = { }.
hash4 = {'c' => 4, 'd' => 3, 'e' = 5}。
預期的結果
hash1 == hash2 # => true
hash1 == hash3 # => true
hash1 == hash4 # => false(沒有共同的鍵來比較它們的值)
hash2 == hash3 # => true
所以基本上我想在比較時,比較兩個哈希中相同鍵的值。如果沒有共同的鍵,則給出false
編輯:我想比較兩個哈希值中相同的鍵。
編輯。 給@CarySwoveland的提示,他的解決方案完美地作業:
common_keys = hash1.key & hash2.key。
if common_keys.any?
hash1.values_at(*common_keys) == hash2.values_at(*common_keys)。
else
false[/span
end end
uj5u.com熱心網友回復:
你可以使用Set,如果我得到正確的答案,并檢查第一個哈希值是否包含在第二個哈希值中:
require 'set'
def is_included?(hash_a, hash_b)
return hash_a.size ==(hash_a.to_set & hash_b.to_set).size
結束。
所以,你可以這樣檢查:
hash1 = {'a'/span> => 1, 'b'/span> => 2}。
hash2 = {'a' => 1, 'b' => 2, 'd' => 3} hash3 = {, 'd' => 3 }
hash3 = {'a' => 1, 'b' => 2, 'c' => 4, 'd' => 3}hash4 = { }.
hash4 = {'c' => 4, 'd' => 3, 'e' => 5}。
is_included? (hash1, hash2) #=> true。
is_included?(hash1, hash3) #=> true
is_included? (hash1, hash4) #=> false
is_included? (hash2, hash3) #=> true
另外只要return hash_a.to_set <= hash_b.to_set就應該可以了。
uj5u.com熱心網友回復:
編輯:這個解決方案對原問題中沒有提到的一些情況不起作用,所以這個答案應該更適合。https://stackoverflow.com/a/69280216/299774
這個公式會給你帶來你想要的東西(對于所提供的例子)
def compare(first, second)
((first.to_a & second.to_a) <=> first.to_a) >=0
結束。
它是如何作業的?
它將哈希值轉化為鍵值對的陣列(也是陣列)
> hash1.to_a
=> [["a"/span>, 1], ["b"/span>, 2]
所以現在你可以做一些整潔的事情,把陣列當作集合,并找到它們的交叉點(公共元素):
> hash1.to_a & hash2.to_a
=> [["a"/span>, 1], ["b"/span>, 2]
> hash1.to_a & hash4.to_a
=>[]
剩下的就是檢查交叉點是否包含在這些陣列中,火箭方法<=>非常有用,當陣列相同時將給你0,如果右邊的陣列包含在左邊的陣列中,則給你1,否則給你1。你似乎對前兩種情況感興趣,因此>=0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334290.html
標籤:
