ruby-on-railsrubystringruby-2.1

Check whether a string contains one of multiple substrings


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

Solution

  • Try parens in the expression:

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