检查字符串是否包含 Ruby 数组中的任何子字符串 [英] Check if string contains any substring in an array in Ruby

查看:54
本文介绍了检查字符串是否包含 Ruby 数组中的任何子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

我认为我们可以将这个问题分为两部分:

I think we can divide this question in two:

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

第一个在上面得到了很好的回答.第二,我会做以下事情:

The first is well answered above. For the second, I would do the following:

(cleaned_content_types - VALID_CONTENT_TYPES) == 0

这个解决方案的好处是你可以轻松地创建一个变量来存储不需要的类型,以便稍后像这个例子一样列出它们:

The nice thing about this solution is that you can easily create a variable to store the undesired types to list them later like this example:

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

这篇关于检查字符串是否包含 Ruby 数组中的任何子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆