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 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts