Rails

How To Determine If An Array Contains Any Value From Another Array In Ruby

Posted by Weston Ganger on September 27, 2016

If you need to find out if one array contains any value from another array, here are a couple methods.


animals = ['cats','dogs','fish']
mammals = ['cats','elephants']
sea_creatures = ['fish','dolphins']

# Get the intersection
animals & mammals #=> ['cats']

# Method 1 - Fastest
(animals & mammals).empty? # false
(mammals & sea_creatures).empty? # true

# Method 2 - Readable
animals.any?{|x| mammals.include?(x)} # true
mammals.any?{|x| sea_creatures.include?(x)} # false


Related External Links:


Posted in Rails and Tagged with ruby array 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts