Dave Dave - 1 month ago 7
Ruby Question

In Rails, how do I perform an intersect of two arrays based on a field in each object in the arrays?

I’m using Rails 4.2.7. I have two arrays, (arr1 and arr2) that both contain my model objects. Is there a way to do an intersection on both arrays if an object from arr1 has a field, “myfield1,” (which is a number) that matches an object in arr2? Both arrays will have unique sets of objects. Currently I have

arr1.each_with_index do |my_object, index|
arr2.each_with_index do |my_object2, index|
if my_object.myfield1 == my_object2.myfield1
results.push(my_object)
end
end
end


but this strikes me as somewhat inefficient. I figure there’s a simpler way to get the results I need but am not versed enough in Ruby to know how to do it.

Answer

You can build an intersection of the values to find the common values, then select records that have the common values.

field_in_both = arr1.map(&:myfield1) & arr2.map(&:myfield1)
intersection = arr1.select{|obj| field_in_both.include? obj.myfield1} + 
               arr2.select{|obj| field_in_both.include? obj.myfield1}

I notice in your code, you're only storing records from arr1... if that's correct behaviour then you can simplify my answer

field_in_both = arr1.map(&:myfield1) & arr2.map(&:myfield1)
intersection = arr1.select{|obj| field_in_both.include? obj.myfield1}
Comments