Skip to content

Fix incorrect autocorrect when Style/NumericPredicate is used with negations#12881

Merged
koic merged 1 commit intorubocop:masterfrom
fatkodima:fix-numeric_predicate-autocorrect
May 3, 2024
Merged

Fix incorrect autocorrect when Style/NumericPredicate is used with negations#12881
koic merged 1 commit intorubocop:masterfrom
fatkodima:fix-numeric_predicate-autocorrect

Conversation

@fatkodima
Copy link
Contributor

When using Style/NumericPredicate cop with EnforcedStyle: comparison and having some negations, rubocop suggests invalid autocorrections.

For example:

!foo.zero?

# Suggests to convert to
!foo == 0

# But should be
foo != 0

In this PR, I did the simplest change possible to just wrap the autocorrected code in the parentheses and it is assumed then after this other cops will convert it from !(foo == 0) to something like foo != 0. Which is actually the case.


expect_correction(<<~RUBY)
number == 0
(number == 0)
Copy link
Member

Choose a reason for hiding this comment

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

Parentheses should not be added when it is not needed.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Made updates.


expect_correction(<<~RUBY)
number > 0
(number > 0)
Copy link
Member

Choose a reason for hiding this comment

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

Ditto.


expect_correction(<<~RUBY)
number < 0
(number < 0)
Copy link
Member

Choose a reason for hiding this comment

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

Ditto.

@fatkodima fatkodima force-pushed the fix-numeric_predicate-autocorrect branch from a8c58c5 to 28ce72d Compare May 3, 2024 15:09
Comment on lines +163 to +164
parent = node.parent
parent&.send_type? && parent&.method?(:!)
Copy link
Member

Choose a reason for hiding this comment

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

Can you refactor to the following?

Suggested change
parent = node.parent
parent&.send_type? && parent&.method?(:!)
return false unless (parent = node.parent)
parent.send_type? && parent.method?(:!)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated.

@fatkodima fatkodima force-pushed the fix-numeric_predicate-autocorrect branch from 28ce72d to bfbc4bf Compare May 3, 2024 15:24
@koic koic merged commit 9c67edf into rubocop:master May 3, 2024
@koic
Copy link
Member

koic commented May 3, 2024

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants