MrAutoIt MrAutoIt - 1 year ago 129
Ruby Question

Compare two array for missing elements in Ruby

I have two arrays that have thousands of elements. I need to find what elements are missing in one array by comparing it to another. Is there a way to get the missing elements without iterating through the entire array? Or is there something faster than what I am doing?

Here is what I am using now:

def find_missing(array1, array2)
missing_elements = []
array1.each { |e|
unless array2.include? e
missing_elements << e

return missing_elements

array1 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
array2 = [1, 2, 4, 5, 6, 7, 9]

puts find_missing(array1, array2)

Answer Source

You want a copy of the first array, but removing any elements that appears in the second array? That's what Array#- (array difference) does:

array1 - array2
# => [10, 8, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download