How to determine if one array contains all elements of another array How to determine if one array contains all elements of another array arrays arrays

How to determine if one array contains all elements of another array


a = [5, 1, 6, 14, 2, 8]b = [2, 6, 15]a - b# => [5, 1, 14, 8]b - a# => [15](b - a).empty?# => false


Perhaps this is easier to read:

a2.all? { |e| a1.include?(e) }

You can also use array intersection:

(a1 & a2).size == a1.size

Note that size is used here just for speed, you can also do (slower):

(a1 & a2) == a1

But I guess the first is more readable. These 3 are plain ruby (not rails).


This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).