Check if string contains any substring in an array in Ruby

So if we just want existence of a match:

VALID_CONTENT_TYPES.inject(false) do |sofar, type| 
    sofar or attachment.content_type.start_with? type
end

If we want the matches this will give the list of matching strings in the array:

VALID_CONTENT_TYPES.select { |type| attachment.content_type.start_with? type }

If image/jpeg; name=example3.jpg is a String:

("image/jpeg; name=example3.jpg".split("; ") & VALID_CONTENT_TYPES).length > 0

i.e. intersection (elements common to the two arrays) of VALID_CONTENT_TYPES array and attachment.content_type array (including type) should be greater than 0.

That's at least one of many ways.


There are multiple ways to accomplish that. You could check each string until a match is found using Enumerable#any?:

str = "alo eh tu"
['alo','hola','test'].any? { |word| str.include?(word) }

Though it might be faster to convert the array of strings into a Regexp:

words = ['alo','hola','test']
r = /#{words.join("|")}/ # assuming there are no special chars
r === "alo eh tu"