Ruby Logical Operators - Elements in one but not both arrays Ruby Logical Operators - Elements in one but not both arrays ruby ruby

Ruby Logical Operators - Elements in one but not both arrays


Arrays in Ruby very conveniently overload some math and bitwise operators.

Elements that are in a, but not in b

 a - b # [3]

Elements that are both in a and b

 a & b # [1, 2]

Elements that are in a or b

 a | b # [1, 2, 3]

Sum of arrays (concatenation)

 a + b # [1, 2, 3, 1, 2]

You get the idea.


p (a | b) - (a & b) #=> [3]

Or use sets

require 'set'a.to_set ^ b


There is a third way of looking at this solution, which directly answers the question and does not require the use of sets:

r = (a-b) | (b-a)

(a-b) will give you what is in array a but not b:

a-b=> [3] 

(b-a) will give you what is in array b but not a:

b-a => [] 

OR-ing the two array subtractions will give you final result of anything that is not in both arrays:

r = ab | ba=> [3]

Another example might make this even more clear:

a = [1,2,3]=> [1, 2, 3] b = [2,3,4]=> [2, 3, 4] a-b=> [1] b-a=> [4] r = (a-b) | (b-a)=> [1, 4]