Determining Whether One Array Contains the Contents of Another Array in Ruby

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

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.

Determine if one array contains all elements of another array

class Array
def contains_all? other
other = other.dup
each{|e| if i = other.index(e) then other.delete_at(i) end}
other.empty?
end
end

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.

Array include every value from another array?

You can simply subtract one array from another, if the result is an empty array, all values are contained:

cheeses = %w[brie feta]
foods = %w[feta pizza brie bread]
(cheeses - foods).empty?
#=>true

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

How to check if array shares elements with another array in Ruby?

You can use an intersection to solve this problem instead. The intersection of two arrays is an array containing only the elements present in both. If the intersection is empty, the arrays had nothing in common, else the arrays had the elements from the result in common:

if (current_tags & @user.tags).any?
# ok
end

How to check if a value exists in an array in Ruby

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

How to find if one array is a subset of another array in Ruby?

[b, c, d].map do |arr|
a.each_cons(arr.length).any?(&arr.method(:==))
end
#⇒ [true, false, false]

This is definitely not the most performant solution, but for not huge arrays is works and, which is important, is readable.

Enumerable#each_cons.



Related Topics



Leave a reply



Submit