Regexp.union
在这种情况下是你的朋友。考虑:
# the words we're looking for...
target_words = %w[ore sit ad sint est lore]
search_text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
# define a search ignoring case that looks for partial words...
partial_words_regex = /#{ Regexp.union(target_words).source }/i
partial_words_regex.to_s # => "(?i-mx:ore|sit|ad|sint|est|lore)"
# define a search ignoring case that looks for whole words...
whole_words_regex = /\b(?:#{ Regexp.union(target_words).source })\b/i
whole_words_regex.to_s # => "(?i-mx:\\b(?:ore|sit|ad|sint||lore)\\b)"
# find the first hit...
search_text[whole_words_regex] # => "sit"
# find all partial word hits...
search_text.scan(partial_words_regex) # => ["Lore", "sit", "ad", "ore", "lore", "ad", "lore", "sint", "est"]
# find all whole word hits...
search_text.scan(whole_words_regex) # => ["sit", "ad", "sint", "est"]
把它放在上下文中:
string_1 = "a monkey is an animal. dogs are fun"
arrays_of_strings_to_check_against = ['banana', 'fruit', 'animal', 'dog']
string_1[Regexp.union(arrays_of_strings_to_check_against)] # => "animal"
string_1.scan(Regexp.union(arrays_of_strings_to_check_against)) # => ["animal", "dog"]