I have assumed that, in both people1
and people2
, the values of :name
are unique.
Here's one way to extract the desired pairs.
Code
def extract_pairs(people1, people2)
h2 = people2.each_with_object({}) { |g,h| h.update(g[:name]=>g) }
people1.each_with_object([]) do |g,a|
k = g[:name]
a << [g,h2[k]] if h2.key?(k)
end
end
Example
people1 = [{ name: :jon, id: 1 }, { name: :jay, id: 3 }, { name: :ray, id: 5 }]
people2 = [{ name: :jon, id: 2 }, { name: :ray, id: 7 }]
extract_pairs(people1, people2)
#=> [[{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}],
# [{:name=>:ray, :id=>5}, {:name=>:ray, :id=>7}]]
Explanation
For the above example:
enum0 = people2.each_with_object({})
#=> #<Enumerator: [{:name=>:jon, :id=>2}, {:name=>:ray, :id=>7}]:
# each_with_object({})>
g, h2 = enum0.next
#=> [{:name=>:jon, :id=>2}, {}]
g #=> {:name=>:jon, :id=>2}
h2 #=> {}
h2.update(g[:name]=>g)
#=> {}.update(:jon=>{:name=>:jon, :id=>2})
#=> {:jon=>{:name=>:jon, :id=>2}}
g, h2 = enum0.next
#=> [{:name=>:ray, :id=>7}, {:jon=>{:name=>:jon, :id=>2}}]
h2.update(g[:name]=>g)
#=> {:jon=>{:name=>:jon, :id=>2}}.update(:ray=>{:name=>:ray, :id=>7}
#=> {:jon=>{:name=>:jon, :id=>2}, :ray=>{:name=>:ray, :id=>7}}
enum1 = people1.each_with_object([])
#=> #<Enumerator: [{:name=>:jon, :id=>1}, {:name=>:jay, :id=>3},
# {:name=>:ray, :id=>5}]:each_with_object([])>
g, a = enum1.next
#=> [{:name=>:jon, :id=>1}, []]
k = g[:name]
#=> :jon
a << [g,h2[k]] if h2.key?(k)
# [] << [{:name=>:jon, :id=>1},
# {:jon=>{:name=>:jon, :id=>2}, :ray=>{:name=>:ray, :id=>7}}[:jon] if
# {:jon=>{:name=>:jon, :id=>2}, :ray=>{:name=>:ray, :id=>7}}.key?(:jon)
# [] << [{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}] if true
a #=> [{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}]
g, a = enum1.next
#=> [{:name=>:jay, :id=>3},
# [[{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}]]]
k = g[:name]
#=> :jay
a << [g,h2[k]] if h2.key?(k)
#=> nil
g, a = enum1.next
#=> [{:name=>:ray, :id=>5},
# [[{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}]]]
k = g[:name]
#=> :ray
a << [g,h2[k]] if h2.key?(k)
#=> [[{:name=>:jon, :id=>1}, {:name=>:jon, :id=>2}],
# [{:name=>:ray, :id=>5}, {:name=>:ray, :id=>7}]]