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
Autocorrect Style/HashTransformValues is broken #7767
Comments
Using By the way, could you show me the reproduction example code of the issue? |
Hi @koic! 👋 I have a reproduction example code: [[1, 2], [3, 4]].map { |k, v| [k, [v, nil]] }.to_h
# => {1=>[2, nil], 3=>[4, nil]} When I run code.rb:3:1: C: Style/HashTransformValues: Prefer transform_values over map {...}.to_h.
[[1, 2], [3, 4]].map { |k, v| [k, [v, nil]] }.to_h And running -[[1, 2], [3, 4]].map { |k, v| [k, [v, nil]] }.to_h
+[[1, 2], [3, 4]].transform_values { |v| [v, nil] } However, the produced (above) code isn't valid: [[1, 2], [3, 4]].transform_values { |v| [v, nil] }
# NoMethodError: undefined method `transform_values' for [[1, 2], [3, 4]]:Array |
@koic I think this cop should skip array literals? |
Surely Array instance does not have the |
Also the |
… and `Style/HashTransformKeys` Closes rubocop#7767
[Fix #7767] Skip array literals in `Style/HashTransformValues` & `Style/HashTransformKeys`
This is not limited to literals though. In our codebase I found hit rate of this rule (and other similar hash-related rules) to be about 60% overall. For example, this is also considered a hit:
Even though Just in general, this check reacts to the code pattern, but doesn't always make sure that the receiver object is actually a hash. |
Firstly, it transforms some usages of
each_with_object
where the receiver is an Array.Secondly, looking up a missing value in the resulting hash will return a
Proc
object, instead ofnil
.This is not a safe transformation.
The text was updated successfully, but these errors were encountered: