Check if string contains any substring in an array in Ruby

后端 未结 5 1539
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 12:25

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

5条回答
  •  忘掉有多难
    2020-12-28 12:56

    There are multiple ways to accomplish that. You could check each string until a match is found using Enumerable#any?:

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

    Though it might be faster to convert the array of strings into a Regexp:

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

提交回复
热议问题