1

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)
0

2 Answers 2

3

You can simply subtract one array from another, if the result is an empty array, all values are contained:

cheeses = %w[brie feta]
foods = %w[feta pizza brie bread]  
(cheeses - foods).empty?
#=>true
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.