Check whether a string contains one of multiple substrings

66,080

Solution 1

Try parens in the expression:

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

Solution 2

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

Solution 3

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

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

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

Solution 5

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

needles = ["whatever", "pretty"]

if haystack.match?(Regexp.union(needles))
  ...
end
Share:
66,080
Hedge
Author by

Hedge

Updated on July 25, 2022

Comments

  • Hedge
    Hedge almost 2 years

    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
    
  • emery
    emery over 8 years
    also works with .all? if you wanted AND logic instead of OR logic. Thanks, seph!
  • daybreaker
    daybreaker almost 8 years
    this is the better answer if you need to be flexible with the amount of needles. needles = [obj1, obj2, ..., objN]; needles.any? { |needle| haystack.include? needle }
  • RobinSH
    RobinSH about 7 years
    Your code has a typo, it should be match no question mark.
  • emlai
    emlai about 7 years
    @SephCordovano How am I using it wrong and how can I correct it? To me it looks exactly the same as the match? method documentation example linked above.
  • Wassim Dhif
    Wassim Dhif over 6 years
    Can't believe that was it. Thank you.
  • Redoman
    Redoman over 6 years
    @SephCordovano your comment is confusing. You should either expand it or delete it.
  • Seph Cordovano
    Seph Cordovano over 6 years
    @jj_What's confusing about it? If you want to search for an array of substrings you use a union.
  • Sgnl
    Sgnl about 6 years
    Please check your Ruby version before commenting. 2.4.0 has match? whereas previous Ruby versions did not have this method. Added a caveat to the answer to help address some of the comments mentioned here.
  • Joshua Pinter
    Joshua Pinter about 5 years
    This is a fantastic answer. Clean and scalable.