Ruby Array.diff(other) difference between 2 Arrays

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.

5 thoughts on “Ruby Array.diff(other) difference between 2 Arrays

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s