17

Suppose I have the following Ruby code:

array_1 = ['a', 'b']
array_2 = ['a', 'b', 'c']

some_function(array_1, array_2) # => True
some_function(array_2, array_1) # => False
some_function(['a', 'b'], ['a', 'd']) # => False
some_function(['x', 'y'], array_2) # => False

I am pretty much looking for some_function to return True when Parameter 2 contains all of the elements in Parameter 1.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Mike
  • 19,267
  • 11
  • 56
  • 72

3 Answers3

42
def f a,b
    (a-b).empty?
end
Nakilon
  • 34,866
  • 14
  • 107
  • 142
1

From a previous post,

def f a,b
    (a-b).empty?
end

will not work the way you expect, for example:

a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a2 = [2, 3, 5, 9]

(a1-a2).empty? # returns true

however,

a1-a2 # returns [1, 4, 6, 7, 8], not empty

thus f returns false.

A more accurate solution, if you want a one-liner would be:

def f a,b
    a&b == b
end

a&b will return all elements that are in both a and b then we check to see if that is equal to b

For ambiguity sake:

def f a,b
    (a&b == a) || (a&b == b)
end
Iggloo Dev
  • 19
  • 3
  • 1
    This is because you should put bigger array in the first place. Author actually asks whether array `a` is a subset of `b`. Obviously, in your example `a1` is not a subset of `a2` – Nick Roz Sep 12 '16 at 18:52
  • 1
    `a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]` ; `a2 = [2, 3, 5, 9]` ; `(a1-a2).empty?` # => returns `false` !! ; Did I do something wrong or did you?? – Djunzu Oct 15 '17 at 20:37
-2
def f a,b
    tmp  = a.map(|i| b.include?(i))
    tmp.include?(false)
end
Hady Elsahar
  • 2,121
  • 4
  • 29
  • 47