7

I am trying to compare two Ruby arrays to verify that all of the first array's elements are included in the second one. (The reverse isn't needed.)

For example:

a = ["hello", "goodbye"]
b = ["hello", "goodbye", "orange"]

This should return true.

However, I can't figure out a method that will allow me to do this. Any help would be appreciated!

1
  • 1
    You are correct, thank you! My apologies for the duplicate. However, at this point I am unable to delete the question as there are already answers. Only a moderator can delete it. Commented Jun 29, 2013 at 0:39

2 Answers 2

10

Many ways are there to check the same :

a = ["hello", "goodbye"]
b = ["hello", "goodbye", "orange"]
(a - b).empty? # => true
a.all?{|i| b.include? i }
# => true

a = ["hello", "welcome"]
b = ["hello", "goodbye", "orange"]
(a - b).empty? # => false
a.all?{|i| b.include? i }
# => false
Sign up to request clarification or add additional context in comments.

Comments

9

Array set logic is nice here:

a & b == a

a & b produces a new array consisting of the elements that exist in both a and b. You can then test it against a to make sure that the cross section contains all of the elements of a itself. See the manual entry on Array#& for more details.

1 Comment

Note that this is no good if there are duplicate values. For example, a=[1,1,2]; b=[1,2,3]; p a&b==a #=> false since a&b == [1,2]. Per the duplicate question's answer, (a-b).empty? is perhaps a better bet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.