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
Author by
Hedge
Updated on July 25, 2022Comments
-
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 over 8 yearsalso works with .all? if you wanted AND logic instead of OR logic. Thanks, seph!
-
daybreaker almost 8 yearsthis 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 about 7 yearsYour code has a typo, it should be
match
no question mark. -
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 over 6 yearsCan't believe that was it. Thank you.
-
Redoman over 6 years@SephCordovano your comment is confusing. You should either expand it or delete it.
-
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 about 6 yearsPlease 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 about 5 yearsThis is a fantastic answer. Clean and scalable.