0

Is there a way to check whether a string contains any substring in an array?

Say I have bad_words = ['broccoli', 'cabbage', 'kale'], and my_string = "My shopping list features pizza, gummy bears, kale, and vodka." I want to check whether my_string has any of the bad_words items within it without using a loop/iterator. Is this possible?

It seems like people use Array#index to solve this problem, but I'm not sure how because, in my tests, it only returns true if the entire argument matches an entire item from the array: bad_words.index "kale" returns an index but bad_words.index "no kale" returns nil. So it's no good for substrings.

1 Answer 1

1
my_string =~ /\b#{Regexp.union(bad_words)}\b/
#=> 46

will do.

Sign up to request clarification or add additional context in comments.

1 Comment

Clever and effective, I wouldn't have thought of this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.