简体   繁体   中英

Given two arrays of hashes, How can we match hashes from both arrays that have a matching key:value

In Ruby and given two arrays of hashes. How can we match which hashes from these two arrays both match the same specific key: value of those hashes?

Example

A = [{ "Jane Doe" => 10, "Jim Doe" => 6 }, { "Jane Doe" => 11, "Jim Doe" => 12 }, ...]
B = [{ "Jane Doe" => 10, "Jim Doe" => 5 }, { "Jane Doe" => 12, "Jim Doe" => 1 }, ...]

Comparing arrays A and B. We would iterate over all hashes in A and B. We are looking for the key "Jane Doe" with the value 10. We see that "Jane Doe" => 10 is the same in both arrays for index 0. we return the whole hash for both arrays as they have different info for the key "Jim Doe".

The result from the script could be the returning of both matches hashes. One from A and one from B. Or if we are iterating first over A and our inner iteration is over B, trying to match to A then we could just return the matched hash from B.

any idea on how to do this?

matched_results = []

a.each do |h1|
  b.each do |h2|
    if (h1.keys & h2.keys).all? {|k| h1[k] == h2[k]}
      matched_results << h1
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM