检查字符串是否包含Ruby中数组中的任何子字符串
我正在使用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中这样做的最佳方式是什么?
有多种方法可以实现这一目标。 你可以检查每个字符串,直到使用Enumerable#any?
找到匹配项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"
所以,如果我们只想要一个匹配的存在:
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 }
如果是image/jpeg; name=example3.jpg
image/jpeg; name=example3.jpg
是一个字符串:
("image/jpeg; name=example3.jpg".split("; ") & VALID_CONTENT_TYPES).length > 0
VALID_CONTENT_TYPES数组的交集(两个数组共有的元素)和attachment.content_type
数组(包括类型)应该大于0。
这至少是众多方式中的一种。
# will be true if the content type is included VALID_CONTENT_TYPES.include? attachment.content_type.gsub!(/^(image\/[az]+).+$/, "\1")