Ruby 2.7 deprecates Regexp#match and Regexp#match? with a nil argument

Before

Before Ruby 2.7, Regexp#match returns nil when nil argument is passed to it. Whereas Regexp#match? returns false with a nil argument.

name = nil
/^Ruby[a-zA-Z]*/.match(name)
=> nil

/^Ruby[a-zA-Z]*/.match?(name)
=> false

In Ruby 2.7

With Ruby 2.7, Regexp#match and Regexp#match? with a nil argument will display a warning.

name = nil
/^Ruby[a-zA-Z]*/.match(name)
warning: given argument is nil; this will raise a TypeError in the next release
=> nil
 
/^Ruby[a-zA-Z]*/.match?(name)
warning: given argument is nil; this will raise a TypeError in the next release
=> false

The plan is to make these methods raise TypeError in the next version i.e. Ruby 3.0.

The change is done in order to match the behavior of String#match and String#match?

"ruby".match(nil)
TypeError (wrong argument type nil (expected Regexp))

"ruby".match?(nil)
TypeError (wrong argument type nil (expected Regexp))

Initial implementation had deprecated use of Regexp#match and Regexp#match? with a nil argument without any warning.

The change was backward incompatible and it was resulting in need to change Rails and many other gems as they were dependent on /regex/.match?(nil) to return false.

Later, it got reverted to display only warning for Ruby 2.7.

Changes required before Ruby 3.0

The warning can be handled by adding check on presence of the argument getting passed to the Regexp#match and Regexp#match?

name && /^Ruby[a-zA-Z]*/.match?(name)
=> nil

Need help on your Ruby on Rails or React project?

Join Our Newsletter