Is there any method to check if array A contains all the elements of array B?
8 Answers
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}
6 Comments
Ryan Bigg
+1 for
(a-b).empty?oseiskar
Just in case someone ends up here: these are all wrong. The correct answer is
(b-a).empty?, not the other way around. Others are just plain wrong. See also stackoverflow.com/questions/7387937/…fl00r
@oseiskar no, they are not wrong. It depends on the task.
oseiskar
I don't think so. If the task is to answer the question does array A contain all elements of array B, which quite literally translates to Ruby as
B.map{|e|A.include?(e)}.all?, then none of these give the correct answer in the generic case (or, e.g., the first example I came up with: A = [1,2,3], B = [1,2]).fl00r
@oseiskar yes, this sounds reasonable. In generic case they all wrong.
|
This should work for what you need:
(a & b) == b
4 Comments
fl00r
this won't work as a rule.
a = [1,2,2,1,3]; b = [3,2,1]; (a & b) == b => falsethe Tin Man
Yes, but
a = [1,2,2,1,3]; b = [3,2,1]; (a & b).sort == b.sort => truefl00r
@the Tin Man, Yes, but a = [1,2,2,1,3]; b = [3,2,2,1]; (a & b).sort == b.sort => false
Will
no need to sort just reverse the order of the binary AND
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
Comments
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!
Comments
You may want to check out the Set class in the Ruby Standard library. The proper_subset? method will probably do what you want.
differencein 2.6 which provides a perfect fast and readable solution for this. More info here.