2

In ruby you can intersect two arrays using the & operator.
I'm trying to obtain the remainder of the intersection.

If I use a simple case - is sufficient:

array_1 = [0, 1]
array_2 = [0]
array_1 - array_2 => [1]

Now imagine we have 0 appearing multiple times in the first array

array_1 = [0, 0, 1]
array_2 = [0]
array_1 - array_2 => [1]

I would like to know the easiest way to obtain the difference between the first array and the intersection of the first array and the second array

array_1 = [0, 0, 1]
array_2 = [0]
array_1 ??? array_2 => [0, 1]
3
  • 1
    I think this is what you're looking for. Commented May 19, 2018 at 11:36
  • Actually, "opposite of intersection" is misleading. I understand it as a request for "complement of AND", and that would be so-called symmetric difference, or XOR in short. Check here for a quick example how to calculate it for arrays stackoverflow.com/a/4198470/717732 . However, keep in mind that XOR is very simple and may not fully handle duplicate items in either array. If you don't mean XOR, please think of some better way of naming your request than "opposite of &" because it's really confusing. Commented May 20, 2018 at 7:16
  • For example, if Cary's answer suits your needs, then I'd consider calling your goal something along "removing specific items from array".. Commented May 20, 2018 at 7:17

1 Answer 1

2

I have proposed the method I think you want be added to the Ruby core. See the link for examples of its use.

class Array
  def difference(other)
    h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
    reject { |e| h[e] > 0 && h[e] -= 1 }
  end
end

a = [1,2,3,4,3,2,2,4] 
b = [2,3,4,4,4]

a.difference b
  #=> [1, 3, 2, 2] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.