Two-List Common Values ​​Method

Does Ruby have a method that I could use when I have 2 arrays (lists) and I want to get an array (list) of only the values ​​common to both arrays? Like this..

a = [1,2,3] b = [3,4,5] => the method would return [3] 

Conversely, values ​​that are “unique” in these arrays (lists).

 a = [1,2,3] b = [3,4,5] => the method would return [1,2,4,5] 
+4
source share
2 answers
 AND : a & b 

Ruby does not have XOR methods for arrays, so you can do this with other methods. Here are two ways:

 XOR : (a | b) - (a & b) XOR : (a + b) - (a & b) # this result can have duplicates! XOR : (a - b) | (b - a) XOR : (a - b) + (b - a) # this result can have duplicates! 
+2
source

The words you are looking for are intersection and symmetrical difference . AFAIK is in Ruby:

 [1,2,3] & [3,4,5] = [3] [1,2,3] ^ [3,4,5] = [1,2,4,5] 
+2
source

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


All Articles