Relted to Array include any value from another array?, how do we find if all elements from an array are included in another array?
cheeses = %w(brie feta)
foods = %w(feta pizza brie bread)
Relted to Array include any value from another array?, how do we find if all elements from an array are included in another array?
cheeses = %w(brie feta)
foods = %w(feta pizza brie bread)
We can use a method similar to the second highest rated solution in the linked post, leveraging all? instead of any?.
There is the important distinction that the array order matters. The first one must be the smallest. This makes intuitive sense — an array of two items cannot include all the items of an array of four.
cheeses.all? { |cheese| foods.include?(cheese) } # => true
But now we may look at the highest rated answer on that other post and wish we could do it that way. We can, by comparing the intersection of both arrays to the entirety of the smallest. If they match, it means all the words in the smallest array are included in the largest. Here order also matters, but it may not be immediately obvious why.
cheeses & foods == cheeses # => true
foods & cheeses == cheeses # => false
The second case failed because the order of the items in the arrays are different.
cheeses & foods # => ["brie", "feta"]
foods & cheeses # => ["feta", "brie"]
This might be difficult to catch because if the original arrays followed the same order it wouldn’t have made a difference. The thing to remember is that & will keep the order of the first array, so make sure that one is the one you’ll be comparing against.
Alternatively, sort the results and you won’t have to worry about order.
(foods & cheeses).sort == cheeses.sort # => true