Check whether a string contains one of multiple su

2019-01-31 17:31发布

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 = 'whatever'
needle2 = 'pretty'

Now I'd need a disjunction like this which doesn't work in Ruby though:

if haystack.include? needle1 || haystack.include? needle2
    puts "needle found within haystack"
end

7条回答
ら.Afraid
2楼-- · 2019-01-31 18:12

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') }
查看更多
放我归山
3楼-- · 2019-01-31 18:13

Try parens in the expression:

 haystack.include?(needle1) || haystack.include?(needle2)
查看更多
倾城 Initia
4楼-- · 2019-01-31 18:13

For an array of substrings to search for I'd recommend

needles = ["whatever", "pretty"]

if haystack.match(Regexp.union(needles))
  ...
end
查看更多
何必那么认真
5楼-- · 2019-01-31 18:17

To check if contains at least one of two substrings:

haystack[/whatever|pretty/]

Returns first result found

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-31 18:19
(haystack.split & [needle1, needle2]).any?

To use comma as separator: split(',')

查看更多
何必那么认真
7楼-- · 2019-01-31 18:22

If Ruby 2.4, you can do a regex match using | (or):

if haystack.match? /whatever|pretty|something/
  …
end

Or if your strings are in an array:

if haystack.match? Regex.union(strings)
  …
end

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

查看更多
登录 后发表回答