a = [{"b"=>123,"c"=>456}, {"b"=>456,"c"=>555}]
b = [{"c"=>456,"d"=>789}, {"b"=>222,"c"=>444}]
def merge_hashes_with_equal_values(array_of_hashes, key)
array_of_hashes.sort { |a,b| a[key] <=> b[key] }.
chunk { |h| h[key] }.
each_with_object([]) { |h, result| result << h.last.inject(&:merge) }
end
p merge_hashes_with_equal_values(a + b, 'c')
# => [{"b"=>222, "c"=>444}, {"c"=>456, "d"=>789, "b"=>123}, {"b"=>456, "c"=>555}]
首先連接數組,然後傳遞它到散列鍵合併的方法。對該數組進行排序,然後將哈希值在另一個數組中相互合併,這使合併更容易編程。在這裏,我選擇了#chunk來處理用相同的鍵合併檢測連續運行的散列,並使用#each_with_object來編譯最終數組。
由於此方法需要一個數組來處理,所以起始數組的長度不需要相等,並且這些數組的排序並不重要。缺點是操作的密鑰必須包含一個可排序的值(例如,不包含nils)。
這裏又是一個解決問題的方法,這其中使用哈希來構建結果:
def merge_hashes_with_equal_values(array_of_hashes, key)
result = Hash.new { |h,k| h[k] = {} }
remainder = []
array_of_hashes.each_with_object(result) do |h, answer|
if h.has_key?(key)
answer[h.fetch(key)].merge!(h)
else
remainder << h
end
end.values + remainder
end
任何一個可以回答這個https://stackoverflow.com/questions/44748498/is-there- any-way-to-check-if-hashes-in-an-an-array-contains-similar-key-value-pairs – Robin