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!
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.
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 .
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With