str1 = "a monkey is an animal. dogs are fun" str2 = "a monkey is a primate. dogs are fun" words = %w[banana fruit animal dog] word_test = /\b(?:#{ words.map{|w| Regexp.escape(w) }.join("|") })\b/i p str1 =~ word_test,
If you received nil , there was no match; otherwise, you get an integer (which can be treated exactly like true ), which is the offset index where the match occurred.
If you absolutely must have true or false , you can do:
any_match = !!(str =~ word_test)
A regular expression created by interpolation:
/\b(?:banana|fruit|animal|dog)\b/i
... where \b matches the "word boundary", thereby preventing dog from matching in dogs .
Change The above answer no longer uses Regexp.union , as this creates a case-sensitive regular expression, while the question requires case-insensitive.
Alternatively, we can force everyone to execute lowercase letters before the test to get case insensitive:
words = %w[baNanA Fruit ANIMAL dog] word_test = /\b#{ Regexp.union(words.map(&:downcase)) }\b/ p str1.downcase =~ word_test, str2.downcase =~ word_test
source share