Checking for Ruby Array Elements in Another Array

I am trying to compare two Ruby arrays to make sure that all the first elements of the array are included in the second. (Reverse is not needed.)

For instance:

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

This should return true.

However, I cannot understand the method that will allow me to do this. Any help would be appreciated!

+4
source share
2 answers

There are many ways to verify the same thing:

 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 
+8
source

The array set logic is good here:

 a & b == a 

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

+8
source

Source: https://habr.com/ru/post/1488788/


All Articles