检查字符串是否包含Ruby中数组中的任何子字符串

时间:2012-04-18 18:26:29

标签: ruby regex substring

我正在使用 Tmail库,对于电子邮件中的每个附件,当我执行attachment.content_type时,有时我不仅会获得内容类型,还会获得名称。例子:

image/jpeg; name=example3.jpg

image/jpeg; name=example.jpg

image/jpeg; name=photo.JPG

image/png

我有一系列有效的内容类型,如下所示:

VALID_CONTENT_TYPES = ['image/jpeg']

我希望能够检查内容类型是否包含在任何有效的内容类型数组元素中。

在Ruby中这样做的最佳方式是什么?

5 个答案:

答案 0 :(得分:85)

有多种方法可以实现这一目标。您可以使用Enumerable#any?检查每个字符串,直到找到匹配项为止:

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

虽然将字符串数组转换为Regexp可能会更快:

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

答案 1 :(得分:3)

所以如果我们只想要一个匹配的存在:

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

如果我们想要匹配,这将给出数组中匹配字符串的列表:

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

答案 2 :(得分:2)

如果image/jpeg; name=example3.jpg是字符串:

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

即。 VALID_CONTENT_TYPES数组和attachment.content_type数组(包括类型)的交集(两个数组共有的元素)应大于0。

这至少是许多方式中的一种。

答案 3 :(得分:2)

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

答案 4 :(得分:0)

我认为我们可以将这个问题一分为二:

  1. 如何清除不需要的数据
  2. 如何检查清除的数据是否有效

第一个在上面得到了很好的回答。对于第二个,我将执行以下操作:

(cleaned_content_types - VALID_CONTENT_TYPES) == 0

此解决方案的优点是,您可以轻松地创建一个变量来存储不需要的类型,以在以后的示例中列出它们,如下例所示:

VALID_CONTENT_TYPES = ['image/jpeg']
cleaned_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/jpeg']

undesired_types = cleaned_content_types - VALID_CONTENT_TYPES
if undesired_types.size > 0
  error_message = "The types #{undesired_types.join(', ')} are not allowed"
else
  # The happy path here
end
相关问题