Simple starting place:
words = %w[one two three] /#{ Regexp.union(words).source }/i # => /one|two|three/i
You probably want to make sure that you only match the words, so tweak this:
/\b#{ Regexp.union(words).source }\b/i
For clarity and clarity, I prefer to use the group without capturing:
/\b(?:#{ Regexp.union(words).source })\b/i
Using source is important. When you create a Regexp object, it has an idea of ββthe flags ( i , m , x ) that apply to this object, and they are inserted into the line:
"#{ /foo/i }" # => "(?i-mx:foo)" "#{ /foo/ix }" # => "(?ix-m:foo)" "#{ /foo/ixm }" # => "(?mix:foo)"
or
(/foo/i).to_s # => "(?i-mx:foo)" (/foo/ix).to_s # => "(?ix-m:foo)" (/foo/ixm).to_s # => "(?mix:foo)"
This is good when the generated template stands alone, but when it is interpolated into a string to define other parts of the template, the flags affect each subexpression:
/\b(?:#{ Regexp.union(words) })\b/i
Take a look at the Regexp documentation and you will see that ?-mix disables the "ignore case" inside (?-mix:one|two|three) , even if the generic pattern is marked i , which leads to the pattern that doesn't do what you want and really hard to debug:
'foo ONE bar'[/\b(?:#{ Regexp.union(words) })\b/i]
Instead, source removes the flags of the internal expression, causing the template to do what you expect:
/\b(?:#{ Regexp.union(words).source })\b/i
and
'foo ONE bar'[/\b(?:#{ Regexp.union(words).source })\b/i]
You can create your own templates using Regexp.new and passing flags:
regexp = Regexp.new('(?:one|two|three)', Regexp::EXTENDED | Regexp::IGNORECASE)
but when the expression becomes more complex, it becomes cumbersome. Building a template using string interpolation remains easier to understand.