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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With