How can I get the intersection, union, and subset of arrays in Ruby?

user487743 picture user487743 · Apr 15, 2011 · Viewed 112.8k times · Source

I want to create different methods for a class called Multiset.

I have all the required methods, but I'm unsure of how to write intersection, union, and subset methods.

For intersection and union, my code starts like this:

def intersect(var)
  x = Multiset.new
end

Here is an example:

X = [1, 1, 2, 4]
Y = [1, 2, 2, 2]

then the intersection of X and Y is [1, 2].

Answer

Jon Gauthier picture Jon Gauthier · Apr 15, 2011

I assume X and Y are arrays? If so, there's a very simple way to do this:

x = [1, 1, 2, 4]
y = [1, 2, 2, 2]

# intersection
x & y            # => [1, 2]

# union
x | y            # => [1, 2, 4]

# difference
x - y            # => [4]

Source