I am currently looking for a software/web development job preferably as a Rails-based developer.
Please email me at weston@westonganger.com. Thanks in advance for any leads!

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

Posted by Weston Ganger

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:

Article Topic:Software Development - Rails

Date:September 27, 2016

Recommended Posts