How can I do a strict check on if a Ruby array contains only certain values?

Viewed 1260

I need to check an Array and see if it contains only certain values of another Array.

I can think of ways to do this using the methods map and select and then iterating through the array with includes? but this would be far from efficient.

values = ['2','4','5'] # return true if the array only contains these values...

a = ['1', '2', '3']
b = ['1', '2', '4']
c = ['2', '4']
d = ['4', '5']

def compare(checked_array, standard)
 # Do something
end

So, for my purpose, output should be,

  • check(a, values) would return false
  • check(b, values) would return false
  • check(c, values) would return true
  • check(d, values) would return true
4 Answers

Simple subtraction will provide you desired output,

def compare(checked_array, standard)
 (checked_array - standard).empty?
end

Another way with arrays intersection:

def compare(checked_array, standard)
  (checked_array & standard) == standard
end

Probably not as short and sweet as using subtraction/intersection but here goes:

require "set"
def compare(check_array, standard
    standard.to_set.superset?(check_array.to_set) # return true if check_array is subset of standard
end

You could use Set#subset?:

require 'set'

def compare(checked_array, standard)
 s = Set.new(standard)
 c = Set.new(checked_array)
 c.subset? s
end

As the documentation states:

Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.

Related