Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 638
CodeBiker Avatar asked Jun 28 '13 22:06

CodeBiker


People also ask

How do you check if all elements in an array are present in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How can you test if an item is included in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

How do you check if two arrays have the same element in Ruby?

Ruby arrays may be compared using the ==, <=> and eql? methods. The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.


1 Answers

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
like image 170
Arup Rakshit Avatar answered Sep 22 '22 22:09

Arup Rakshit