Diff is defined on Set, but not on Array, so we patch it in… (thanks to reto)
Usage
[1,2] ^ [2,3,4] == [1,3,4]
Code
class Array def ^(other) result = dup other.each{|e| result.include?(e) ? result.delete(e) : result.push(e) } result end unless method_defined?(:^) alias diff ^ unless method_defined?(:diff) end puts ([] ^ [1]).inspect # [1] puts ([1] ^ []).inspect # [1] puts ([1] ^ [2]).inspect # [1,2] puts ([] ^ []).inspect # [] puts ([1,1] ^ [1,1,2,2]).inspect # [1]
The same could be done with (self | other) – (self & other) but would be less performant.
See also Set#^ which does the same.
Cheers,
reto
Thanks for the tip, just updated the post 🙂
And `require ‘set’` is necessary. If the require statement is missing, `[1,2] ^ [2,3,4]` raises NameError: uninitialized constant Array::Set.
Thanks, fixed!
I rewrote it with the internal implementation from set, so this should be as performant as it gets 🙂