How do you check if an array's values includes one or multiple values?

>> [1,2,3,4,5,6] & [4,1]
=> [1, 4]
>> [1,2,3,4,5,6] & [7,9]
=> []
>>

This is a set operation. Set is in the standard library.

require 'set'

a = Set[1,2,3,4,5,6]
b = Set[4,1]

b.subset? a
#=> true

EDIT: I endorse Mark Thomas' alternate solution that uses the core Set class.

While my solution more strictly answers the question at hand of how to do this with arrays, sjsc may benefit from reviewing his own case and exploring the option of using sets instead.

There are plenty of valid reasond to use arrays (maintaining order, allowing for duplicates), for which the below still suffices, but if none of these are involved, sjsc might actually benefit from using Set instead of Array, and to that extent, Mark's solution is semantically superior.


I don't know of any library method that does this, but it wouldn't be too hard to write your own function.

class Array
  def subset?(a)
    (self - a).length == 0
  end
end

I'm sure there are computationally more efficient ways to accomplish this, but this should do what you're looking for.

Doing array intersection works and basically amounts to the same thing.

class Array
  def subset?(a)
    (self & a).length == length
  end
end

Optimization at this level isn't going to help matters too much, but what you don't want to do is start comparing arrays multiple times:

class Array
  # don't do this
  def subset?(a)
    (self & a) == a
  end
end

Tags:

Arrays

Ruby