How can I do a strict check on if a Ruby array contains only certain values? [duplicate]
Asked Answered
S

4

5

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
Studdard answered 3/7, 2019 at 9:29 Comment(0)
A
8

Simple subtraction will provide you desired output,

def compare(checked_array, standard)
 (checked_array - standard).empty?
end
Arlana answered 3/7, 2019 at 9:33 Comment(1)
This is simple and efficient, thanks! Its one line of code where I would have used 15... much better 👍Studdard
J
4

Another way with arrays intersection:

def compare(checked_array, standard)
  (checked_array & standard) == standard
end
Josie answered 3/7, 2019 at 9:47 Comment(0)
I
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
Ingrid answered 3/7, 2019 at 10:12 Comment(1)
There is no method as superset, its superset? standard.to_set.superset?(check_array.to_set)Gaberdine
P
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.

Pearce answered 3/7, 2019 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.