Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby function to perform an XOR operation on two sets of strings?

Tags:

arrays

ruby

set

I have two Arrays of strings, and I would like to find the set of strings not in the intersection of both. The equivalent of SETXOR in MATLAB is what I want: http://www.mathworks.com/help/techdoc/ref/setxor.html

I'm using the term set interchangeably with Array.

Of course, I could have just as easily written my own in the time taken to form this question, but I thought I should ask.

like image 219
Manu R Avatar asked Nov 16 '10 20:11

Manu R


3 Answers

array1 + array2 - (array1 & array2)

It was shorter, than to write a question...

By the way, Ruby has a class Set, so better not to use this word as a synonym to an Array.

like image 136
Nakilon Avatar answered Oct 04 '22 07:10

Nakilon


Yes, as Nakilon says, Set.

require 'set'
s = Set.new('a'..'f')
a = ['f','d','e','e','h','i'] #or any enum
p s ^ a  #=> #<Set: {"h", "i", "a", "b", "c"}>
like image 21
steenslag Avatar answered Oct 04 '22 06:10

steenslag


You can always just do

(array0 - array1) + (array1 - array0)

a = [1, 2, 3, 4, 5]
b = [2, 5, 8]
(a - b) + (b - a)
  # => [1, 3, 4, 8]
like image 39
Asone Tuhid Avatar answered Oct 04 '22 06:10

Asone Tuhid