Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains any substring in an array in Ruby

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?

like image 537
Hommer Smith Avatar asked Apr 18 '12 18:04

Hommer Smith


People also ask

How do you check if an element exists in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.


1 Answers

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" 
like image 63
cydparser Avatar answered Sep 22 '22 06:09

cydparser