Ruby - Does Array a Contain All Elements of Array B

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

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

Ruby - Does array A contain all elements of array B

This should work for what you need:

(a & b) == b

Array include any value from another array?

(cheeses & foods).empty?

As Marc-André Lafortune said in comments, & works in linear time while any? + include? will be quadratic. For larger sets of data, linear time will be faster. For small data sets, any? + include? may be faster as shown by Lee Jarvis' answer -- probably because & allocates a new Array while another solution does not and works as a simple nested loop to return a boolean.

Checking if a Ruby array's elements are included in another array

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

Determining whether one array contains the contents of another array in ruby

You can use each_cons method:

arr = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].each_cons(arr.size).include? arr

In this case it will work for any elements.

Array.include? multiple values

You could take the intersection of two arrays, and see if it's not empty:

([2, 6, 13, 99, 27] & [2, 6]).any?

Ruby: Array contained in Array, any order

def f a,b
(a-b).empty?
end

How can I check if a Ruby array includes one of several values?

Set intersect them:

a1 & a2

Here's an example:

> a1 = [ 'foo', 'bar' ]
> a2 = [ 'bar', 'baz' ]
> a1 & a2
=> ["bar"]
> !(a1 & a2).empty? # Returns true if there are any elements in common
=> true

Check if two arrays have the same contents (in any order)

This doesn't require conversion to set:

a.sort == b.sort


Related Topics



Leave a reply



Submit