-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
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
Why does Rubocop equate != 0 with #nonzero? #3598
Comments
Hm. This looks like it is just a brain fart on my end. I have only ever used this method in predicate expressions, because I was under the impression that the It seems a lot of people are wrestling with this cop for other reasons, I think this might be the straw that broke the camel's back, and I think we should remove it. (Or at least disable it.) |
One of the many crazy things in the core library. Predicate methods are supposed to return booleans, but I guess the core team forgot this here and there. Amusingly the |
I like this cop but think it should probably have its autocorrect disabled by default because that's sometimes dangerous. Regarding this specific issue, might it be worth limiting the scope of the cop to a whitelist of places where we know that only the truthiness is being checked? Such as So these would still give an offence: call unless number > 0
x = number > 0 ? :a : :b But these no longer would: x = number > 0
return number > 0
expect(number).to be > 0 |
FWIW, this seems like a great solution. |
This cop actually checks for 4 predicates, not just one. All of them except One other option would be to suggest replacing |
I prefer this to my idea. 👍 I was thinking my proposal would offer some extra safety and ease some of the issues people had with the cop in #3371, but on second thought it wouldn't, any benefits would be coincidental. |
Having read through https://bugs.ruby-lang.org/issues/9123 I've come to the conclusion that I want to side with the people who say that there's nothing wrong with So I don't see a need for a new cop to report usages of I suggest that we just avoid auto-correcting |
That's interesting. I am on the other side. 😊 However, I think the real mistake was tacking that I don't think it affects RuboCop that much though. I still side with your proposal on how to handle it. 😀 |
The two expressions are not equivalent. `x != 0` returns `true` or `false` while `x.nonzero?` returns `self`, i.e. `x`, or `nil`.
Rubocop warns that I should
Expected behavior
I'm not sure why this is a warning when the functionality is different.
Actual behavior
Steps to reproduce the problem
RuboCop version
This is not an issue on 0.40
I tried to correct with
!! foo.nonzero?
but that raises another warning.The text was updated successfully, but these errors were encountered: