4

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
ray
  • 5,454
  • 1
  • 18
  • 40
JJdinho
  • 53
  • 5

4 Answers4

7

Simple subtraction will provide you desired output,

def compare(checked_array, standard)
 (checked_array - standard).empty?
end
ray
  • 5,454
  • 1
  • 18
  • 40
  • 1
    This is simple and efficient, thanks! Its one line of code where I would have used 15... much better – JJdinho Jul 03 '19 at 09:59
4

Another way with arrays intersection:

def compare(checked_array, standard)
  (checked_array & standard) == standard
end
Martin
  • 4,042
  • 2
  • 19
  • 29
3

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
Shan
  • 613
  • 9
  • 21
Nick M
  • 2,424
  • 5
  • 34
  • 57
  • 1
    There is no method as superset, its superset? `standard.to_set.superset?(check_array.to_set)` – Shan Jul 03 '19 at 10:35
2

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.

iGian
  • 11,023
  • 3
  • 21
  • 36