Ruby逻辑运算符 - 一个但不是两个数组中的元素

时间:2022-04-04 12:08:34

Let's say I have two arrays:

假设我有两个数组:

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

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

我希望在这两个数组上执行逻辑运算,返回不在两个数组中的元素(即3)。谢谢!

3 个解决方案

#1


14  

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

Ruby中的数组非常方便地重载一些数学和按位运算符。

Elements that are in a, but not in b

在a中但不在b中的元素

 a - b # [3]

Elements that are both in a and b

a和b中的元素

 a & b # [1, 2]

Elements that are in a or b

a或b中的元素

 a | b # [1, 2, 3]

Sum of arrays (concatenation)

数组之和(连接)

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

You get the idea.

你明白了。

#2


9  

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

Or use sets

或者使用套装

require 'set'
a.to_set ^ b

#3


0  

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)会给你数组a但不是b:

a-b
=> [3] 

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

(b-a)将给出数组b中的内容但不是:

b-a 
=> [] 

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

对两个数组减法进行OR运算将为您提供两个数组中不存在的任何结果的最终结果:

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] 

#1


14  

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

Ruby中的数组非常方便地重载一些数学和按位运算符。

Elements that are in a, but not in b

在a中但不在b中的元素

 a - b # [3]

Elements that are both in a and b

a和b中的元素

 a & b # [1, 2]

Elements that are in a or b

a或b中的元素

 a | b # [1, 2, 3]

Sum of arrays (concatenation)

数组之和(连接)

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

You get the idea.

你明白了。

#2


9  

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

Or use sets

或者使用套装

require 'set'
a.to_set ^ b

#3


0  

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)会给你数组a但不是b:

a-b
=> [3] 

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

(b-a)将给出数组b中的内容但不是:

b-a 
=> [] 

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

对两个数组减法进行OR运算将为您提供两个数组中不存在的任何结果的最终结果:

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]