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

Let's say I have two arrays:

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

I want a logical operation to be performed on both of these arrays, which returns elements that are not in both arrays (i.e. 3). Thanks!

+6
source share
3 answers

Arrays in Ruby are very convenient for overloading some mathematical and bitwise operators.

Elements that are in a but not in b

  a - b # [3] 

Elements that are in a and b

  a & b # [1, 2] 

Items in a or b

  a | b # [1, 2, 3] 

Sum of arrays (concatenation)

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

You get the idea.

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

Or use sets

 require 'set' a.to_set ^ b 
+9
source

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

 r = (ab) | (ba) 

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

 ab => [3] 

(ba) will give you what is in array b, but not:

 ba => [] 

OR - subtracting two arrays will give you the final result of something that is not in both arrays:

 r = ab | ba => [3] 

Another example might make this even clearer:

 a = [1,2,3] => [1, 2, 3] b = [2,3,4] => [2, 3, 4] ab => [1] ba => [4] r = (ab) | (ba) => [1, 4] 
0
source

Source: https://habr.com/ru/post/906334/


All Articles