Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 perform on both of these arrays that returns the elements that are not in both arrays (i.e. 3). Thanks!

like image 992
Michael Avatar asked Jan 18 '12 19:01

Michael


People also ask

How do you check if two arrays have the same element in Ruby?

Ruby arrays may be compared using the ==, <=> and eql? methods. The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator. If the arrays are equal, a bool value is returned, which is either true or false .

What does != Mean in Ruby?

Equality: ==, != == is the equality operator. It determines whether two values are equal, according to the lefthand operand's definition of “equal.” The != operator is simply the inverse of == : it calls == and then returns the opposite. You can redefine != in Ruby 1.9 but not in Ruby 1.8.

How can you test if an item is included in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.


3 Answers

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.

like image 156
Sergio Tulentsev Avatar answered Oct 11 '22 12:10

Sergio Tulentsev


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

Or use sets

require 'set'
a.to_set ^ b
like image 31
steenslag Avatar answered Oct 11 '22 13:10

steenslag


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] 
like image 26
Chip Roberson Avatar answered Oct 11 '22 14:10

Chip Roberson