Ruby - Does array A contain all elements of array

2020-03-09 07:22发布

问题:

Is there any method to check if array A contains all the elements of array B?

回答1:

This should work for what you need:

(a & b) == b


回答2:

You can try this

a.sort.uniq == b.sort.uniq

or

(a-b).empty?

And if [1,2,2] != [1,2] in your case you can:

a.group_by{|i| i} == b.group_by{|i| i}


回答3:

You could use Ruby's Set class:

>> require 'set' #=> true
>> a = [*1..5] #=> [1, 2, 3, 4, 5]
>> b = [*1..3] #=> [1, 2, 3]
>> a.to_set.superset? b.to_set #=> true

For small arrays I usually do the same as what fl00r suggested:

>> (b-a).empty? #=> true


回答4:

I prefer to do this via: (b - a).blank? # tells that b is contained in a



回答5:

The simplest way is this:

(b-a).empty?


回答6:

There's also the Set class (part of the standard library) which would allow you to just check to see if B is a subset of A, e.g.

>> a = [1,2,3,4,5]       => [1, 2, 3, 4, 5]
>> b = [3,4,5]           => [3, 4, 5]
>> require 'set'         => true 
>> set_a = a.to_set      => #<Set: {1, 2, 3, 4, 5}> 
>> set_b = b.to_set      => #<Set: {3, 4, 5}> 

>> set_b.subset? set_a   => true

http://www.ruby-doc.org/stdlib/libdoc/set/rdoc/index.html



回答7:

You may want to check out the Set class in the Ruby Standard library. The proper_subset? method will probably do what you want.



回答8:

Ruby 2.6+

Ruby's introduced difference in 2.6 for exactly this purpose.

Very fast, very readable, as follows:

a = [1, 2, 3, 4, 5, 6]
b = [1, 2, 3, 4, 5, 6]

a.difference(b).any?
# => false
a.difference(b.reverse).any?
# => false

a = [1, 2, 3, 4, 5, 6]
b = [1, 2, 3]
a.difference(b).any?
# => true

Hope that helps someone!