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
In Ruby, How to Find Out If a String Is Not in an Array
What Are the Steps Needed to Create and Publish a Rubygem of Your Own
Ruby Refuses to Divide Correctly
Grouping Consecutive Numbers in an Array
Need Help Maximizing 3 Factors in Multiple, Similar Objects and Ordering Appropriately
Rails Helper - How to Get a Helper to Give Me a '<Br/>' (Or Other Markup)
How to Add Syntax Highlighting to Sublime Text 2
Can Someone Please Explain Class << Self to Me
Troubles with Ruby-2.X Installation Using Rvm
Is There a Bug in Ruby Lookbehind Assertions (1.9/2.0)
Ruby Scope of Data After _End_
How to Make Xcode Use the Correct Version of Ruby When Running a Script
Sorting an Array by Two Values
Configuration in Allure to Cucumber in Ruby
Multi Level Block Method Is Generating Issue