Manu R
Manu R

Reputation: 836

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

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.

Upvotes: 15

Views: 10467

Answers (3)

Asone Tuhid
Asone Tuhid

Reputation: 549

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]

Upvotes: 4

steenslag
steenslag

Reputation: 80065

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"}>

Upvotes: 11

Nakilon
Nakilon

Reputation: 35084

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.

Upvotes: 26

Related Questions