Check whether a string contains one of multiple substrings

后端 未结 7 1293
挽巷
挽巷 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:28

    I was trying to find simple way to search multiple substrings in an array and end up with below which answers the question as well. I've added the answer as I know many geeks consider other answers and not the accepted one only.

    haystack.select { |str| str.include?(needle1) || str.include?(needle2) }
    

    and if searching partially:

    haystack.select { |str| str.include?('wat') || str.include?('pre') }
    
    0 讨论(0)
提交回复
热议问题