Skip to content

Instantly share code, notes, and snippets.

@awesome
Created January 21, 2010 17:44
Show Gist options
  • Save awesome/282985 to your computer and use it in GitHub Desktop.
Save awesome/282985 to your computer and use it in GitHub Desktop.
Ruby opposite of array intersection
# Ruby opposite of array intersection... or maybe the method is missing from my brain bc not enough coffee
# http://twitter.com/soawesomeman/status/8035087261
def awesome(ar_1, ar_2)
(ar_1 + ar_2) - (ar_1 & ar_2)
end
awesome([1,2,3,4], [3,4,5,6]) # => [1, 2, 5, 6]
# bonus code from @texel
# http://twitter.com/texel/status/8035307156
(a - (a & b)) | (b - (a & b)) # => nice one!
Copy link

ghost commented Jun 10, 2011

Never mind - I must be tired.

@jpedrojpedro
Copy link

another possible approach - 8 years later... 😓

2.3.1 :001 > a = [1,2,3,4]
 => [1, 2, 3, 4] 
2.3.1 :002 > b = [2,4,6,7,8]
 => [2, 4, 6, 7, 8]
2.3.1 :003 > a - b
 => [1, 3] 
2.3.1 :004 > b - a
 => [6, 7, 8] 
2.3.1 :005 > (a - b) | (b - a)
 => [1, 3, 6, 7, 8]

my first approach was this one:

a.select { |e| !b.include?(e) } + b.select { |e| !a.include?(e) }

I found yours and then I thought about the one I started writing
tks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment