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)
我想我们可以把这个问题一分为二:
第一个问题上面已经回答得很好了。对于第二个,我会执行以下操作:
(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)