Check whether a string contains one of multiple substrings

Ruby on-RailsRubyStringRuby 2.1

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

[needle1, needle2].any? { |needle| haystack.include? needle }

Solution 2 - Ruby on-Rails

Try parens in the expression:

 haystack.include?(needle1) || haystack.include?(needle2)

Solution 3 - Ruby on-Rails

You can do a regex match:

haystack.match? /needle1|needle2/

Or if your needles are in an array:

haystack.match? Regexp.union(needles)

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

Solution 4 - Ruby on-Rails

(haystack.split & [needle1, needle2]).any?

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

Solution 5 - Ruby on-Rails

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

needles = ["whatever", "pretty"]

if haystack.match?(Regexp.union(needles))
  ...
end

Solution 6 - Ruby on-Rails

To check if contains at least one of two substrings:

haystack[/whatever|pretty/]

Returns first result found

Solution 7 - Ruby on-Rails

Use or instead of ||

if haystack.include? needle1 or haystack.include? needle2

or has lower presedence than || , or is "less sticky" if you will :-)

Solution 8 - Ruby on-Rails

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') }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHedgeView Question on Stackoverflow
Solution 1 - Ruby on-RailssephView Answer on Stackoverflow
Solution 2 - Ruby on-RailsdanhView Answer on Stackoverflow
Solution 3 - Ruby on-RailsemlaiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsrgtkView Answer on Stackoverflow
Solution 5 - Ruby on-RailsSeph CordovanoView Answer on Stackoverflow
Solution 6 - Ruby on-RailsKapitula AlexeyView Answer on Stackoverflow
Solution 7 - Ruby on-RailsfoliumView Answer on Stackoverflow
Solution 8 - Ruby on-RailsShikoView Answer on Stackoverflow