Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance/RegexpMatch-20240219233128 #918

Merged
merged 4 commits into from
May 30, 2024

Conversation

github-actions[bot]
Copy link
Contributor

Rubocop challenge!

Performance/RegexpMatch

Safe autocorrect: Yes
✅ The autocorrect a cop does is safe (equivalent) by design.

Description

Overview

In Ruby 2.4, String#match?, Regexp#match?, and Symbol#match?
have been added. The methods are faster than match.
Because the methods avoid creating a MatchData object or saving
backref.
So, when MatchData is not used, use match? instead of match.

Examples

# bad
def foo
  if x =~ /re/
    do_something
  end
end

# bad
def foo
  if x !~ /re/
    do_something
  end
end

# bad
def foo
  if x.match(/re/)
    do_something
  end
end

# bad
def foo
  if /re/ === x
    do_something
  end
end

# good
def foo
  if x.match?(/re/)
    do_something
  end
end

# good
def foo
  if !x.match?(/re/)
    do_something
  end
end

# good
def foo
  if x =~ /re/
    do_something(Regexp.last_match)
  end
end

# good
def foo
  if x.match(/re/)
    do_something($~)
  end
end

# good
def foo
  if /re/ === x
    do_something($~)
  end
end

Auto generated by rubocop_challenger

Copy link
Collaborator

@mathieujobin mathieujobin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we merge this or ignore this rule ?

Copy link
Member

@ekohl ekohl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say this is an improvement. Ruby 3.2 has removed =~ and !~ on non-strings so this code is more reliable as well.

@mathieujobin mathieujobin merged commit 5ba0423 into master May 30, 2024
50 checks passed
@mathieujobin mathieujobin deleted the rubocop-challenge/20240219233128 branch May 30, 2024 02:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants