Check if string contains any substring in an array

2019-02-04 02:04发布

问题:

I am using the Tmail library, and for each attachment in an email, when I do attachment.content_type, sometimes I get not just the content type but also the name. Examples:

image/jpeg; name=example3.jpg

image/jpeg; name=example.jpg

image/jpeg; name=photo.JPG

image/png

I have an array of valid content types like this:

VALID_CONTENT_TYPES = ['image/jpeg']

I would like to be able to check if the content type is included in any of the valid content types array elements.

What would be the best way of doing so in Ruby?

回答1:

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"


回答2:

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 }


回答3:

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.



回答4:

# will be true if the content type is included    
VALID_CONTENT_TYPES.include? attachment.content_type.gsub!(/^(image\/[a-z]+).+$/, "\1")