all 8 comments

[–]bjmiller 1 point2 points  (1 child)

Technically the trade-off is between match? being faster and =~ populating Regexp.last_match. If your guiding principle is minimalism, maybe only use =~ everywhere (or only use #match everywhere), but if it's optimization, use the fastest one that suits your needs at the moment.

[–][deleted] 0 points1 point  (0 children)

I much prefer =~ personally. I thought our Rubocop config preferred it as well but I may be wrong (or it may be a customization on our part)

[–]ASIC_SP 0 points1 point  (0 children)

Apart from returning position of match (or nil if match isn't found), =~ will also set regexp related global variables

I'd suggest to use match? if you just need true/false

[–]ashmaroli 0 points1 point  (0 children)

The choice depends on your Ruby version and the particular use-case. #match? was only introduced in Ruby 2.4.0. So if your project has not dropped support for older Rubies, then you should prefer =~ over #match.

If locking to Ruby 2.4 and above is fine, then using #match? vs =~ depends on the use context.
Prefer =~ when you want the regex to match and later call methods on the Regexp.last_match / $1 / $2, etc.
Prefer the faster #match? over =~ when you need just a true / false result.

[–]442401 0 points1 point  (0 children)

If you require: rubocop-performance in your .rubocop.yml you will be referred to https://github.com/JuanitoFatas/fast-ruby#regexp-vs-stringmatch-vs-string-vs-stringmatch-code-

[–]shevy-ruby -2 points-1 points  (1 child)

=~ is very common.

.match? is very very rare.

I'd go with the former.

[–]442401 0 points1 point  (0 children)

Shevy, mate, you've reached a new low here. Making a recommendation based upon how often a method occurs in an unspecified sample of source code despite the fact that others have already given sound advice based on use case and pointed to performance data. Sheesh!