Hed*_*dge 38 ruby string ruby-on-rails ruby-2.1
我有一个很长的字符串变量,想知道它是否包含两个子串中的一个.
例如
haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'
Run Code Online (Sandbox Code Playgroud)
现在我需要像这样的脱节,但在Ruby中不起作用:
if haystack.include? needle1 || haystack.include? needle2
    puts "needle found within haystack"
end
Run Code Online (Sandbox Code Playgroud)
    sep*_*eph 74
[needle1, needle2].any? { |needle| haystack.include? needle }
Run Code Online (Sandbox Code Playgroud)
        dan*_*anh 46
在表达式中尝试parens:
 haystack.include?(needle1) || haystack.include?(needle2)
Run Code Online (Sandbox Code Playgroud)
        eml*_*lai 11
如果是Ruby 2.4,你可以使用|(或)进行正则表达式匹配:
if haystack.match? /whatever|pretty|something/
  …
end
Run Code Online (Sandbox Code Playgroud)
或者如果您的字符串在数组中:
if haystack.match? Regex.union(strings)
  …
end
Run Code Online (Sandbox Code Playgroud)
(对于Ruby <2.4,请使用.match无问号.)
rgt*_*gtk 10
(haystack.split & [needle1, needle2]).any?
Run Code Online (Sandbox Code Playgroud)
要使用逗号作为分隔符: split(',')
对于要搜索的子串的数组我推荐
needles = ["whatever", "pretty"]
if haystack.match(Regexp.union(needles))
  ...
end
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           47834 次  |  
        
|   最近记录:  |