I am using Ruby on Rails 3.0.7 and I would like to check if each element of an array is included in a set of values present in another array.
That is, I have these arrays:
array1 = [1,3]
array2 = [1,2,3,4,5]
and I would check if values in array1 are all present in the array2. I should return true if at least one of array1 is different from values in array2
How can I code that in a Ruby “good” way?
P.S.: I read this solution, but it is for Java’s arrays.
The easiest thing would be to do a set intersection and see what you get from that:
That would, of course, fail if
array1had duplicates as the intersection will automatically compress those. But we haveuniqto take care of that:If you’re expecting duplicates in your arrays then you’d be better off working with instances of Set rather than arrays:
Or use
subset?to better match your intentions:Using sets will take care of your duplicate issues with less noise than having to use
uniqall the time. There would, of course, be a bit of extra overhead but you should optimize for clarity before performance (make it work then make it fast only if it is too slow).