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

Hom*_*ith 34 ruby regex substring

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

image/jpeg; name=example3.jpg

image/jpeg; name=example.jpg

image/jpeg; name=photo.JPG

image/png
Run Code Online (Sandbox Code Playgroud)

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

VALID_CONTENT_TYPES = ['image/jpeg']
Run Code Online (Sandbox Code Playgroud)

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

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

cyd*_*ser 88

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

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

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

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

  • 我试过两个并尝试对它进行基准测试1_000_000x:`.any?#=>(0.877526)``r = Regexp.union(*words); r === string#=>(17.374344)`仅供参考. (16认同)
  • @Phrogz`Regexp.union(*words)`为你逃跑. (9认同)
  • 几年后,但@index的基准仍然有效,并且仍然适用。现在只有那台机器能更快地处理它。#=>(0.160000); union =>(6.410000)` (2认同)

bon*_*ndo 0

我想我们可以把这个问题一分为二:

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

第一个问题上面已经回答得很好了。对于第二个,我会执行以下操作:

(cleaned_content_types - VALID_CONTENT_TYPES) == 0
Run Code Online (Sandbox Code Playgroud)

这个解决方案的好处是,您可以轻松创建一个变量来存储不需要的类型,以便稍后列出它们,如下例所示:

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
Run Code Online (Sandbox Code Playgroud)