Demo (I expect result [3]):
[1,2] - [1,2,3] => [] # Hmm
[1,2,3] - [1,2] => [3] # I see
a = [1,2].to_set => #<Set: {1, 2}>
b = [1,2,3].to_set => #<Set: {1, 2, 3}>
a - b => #<Set: {}> WTF!
And:
[1,2,9] - [1,2,3] => [9] # Hmm. Would like [[9],[3]]
How is one to perform a real set difference regardless of order of the inputs?
Ps. As an aside, I need to do this for two 2000-element arrays. Usually, array #1 will have fewer elements than array #2, but this is not guaranteed.
The
-operator applied to two arraysaandbgives the relative complement ofbina(items that are inabut not inb).What you are looking for is the symmetric difference of two sets (the union of both relative complements between the two). This will do the trick:
If you are operating on
Setobjects, you may use the overloaded^operator:For extra fun, you could also find the relative complement of the intersection in the union of the two sets: