Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Regexp.union

Regexp.union(*patterns) → regexp
Regexp.union(array_of_patterns) → regexp

Returns a new regexp that is the union of the given patterns:

Example
r = Regexp.union(%w[cat dog])      # => /cat|dog/
r.match('cat')      # => #<MatchData "cat">
r.match('dog')      # => #<MatchData "dog">
r.match('cog')      # => nil

For each pattern that is a string, Regexp.new(pattern) is used:

Example
Regexp.union('penzance')             # => /penzance/
Regexp.union('a+b*c')                # => /a\+b\*c/
Regexp.union('skiing', 'sledding')   # => /skiing|sledding/
Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/

For each pattern that is a regexp, it is used as is, including its flags:

Example
Regexp.union(/foo/i, /bar/m, /baz/x)
# => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
Regexp.union([/foo/i, /bar/m, /baz/x])
# => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/

With no arguments, returns /(?!)/:

Example
Regexp.union # => /(?!)/

If any regexp pattern contains captures, the behavior is unspecified.

See also .try_convert #== .timeout= #=== also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0