Check whether a string contains one of multiple substrings

后端 未结 7 1323
挽巷
挽巷 2020-12-23 19:32

I\'ve got a long string-variable and want to find out whether it contains one of two substrings.

e.g.

haystack = \'this one is pretty long\'
needle1          


        
7条回答
  •  醉话见心
    2020-12-23 20:21

    In Ruby >= 2.4 you can do a regex match using | (or):

    haystack.match? /whatever|pretty|something/
    

    Or if your strings are in an array:

    haystack.match? Regexp.union(strings)
    

    (For Ruby < 2.4, use .match without question mark.)

提交回复
热议问题