-
-
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
Style/HashConversion: Invalid conversion (undefined method `to_h') #9513
Comments
…rsion` Fixes rubocop#9513. This PR fixes an incorrect auto-correct for `Style/HashConversion` when using hash argument `Hash[]`.
Fixes #9513. This PR fixes an incorrect auto-correct for `Style/HashConversion` when using hash argument `Hash[]`.
@bbatsov, I've just experienced this same error in Ruby 2.7.1p83. $ bundle exec rubocop -V
warning: parser/current is loading parser/ruby27, which recognizes
warning: 2.7.2-compliant syntax, but you are running 2.7.1.
warning: please see https://github.com/whitequark/parser#compatibility-with-ruby-mri.
1.10.0 (using Parser 3.0.0.0, rubocop-ast 1.4.1, running on ruby 2.7.1 x86_64-linux) Input file: hash1 = { 'some' => 'value', 'another' => 'value' }
hash2 = { 'some' => 'value'}
hash1_without_hash2 = Hash[hash1.to_a - hash2.to_a]
p hash1_without_hash2 Code result: $ ruby test.rb
{"another"=>"value"} Rubocop execution: $ bundle exec rubocop test.rb
warning: parser/current is loading parser/ruby27, which recognizes
warning: 2.7.2-compliant syntax, but you are running 2.7.1.
warning: please see https://github.com/whitequark/parser#compatibility-with-ruby-mri.
Inspecting 1 file
C
Offenses:
test.rb:3:23: C: [Correctable] Style/HashConversion: Prefer ary.to_h to Hash[ary].
hash1_without_hash2 = Hash[hash1.to_a - hash2.to_a]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1 file inspected, 1 offense detected, 1 offense auto-correctable After the execution of hash1 = { 'some' => 'value', 'another' => 'value' }
hash2 = { 'some' => 'value' }
hash1_without_hash2 = hash1.to_a - hash2.to_a.to_h
p hash1_without_hash2 Now the script causes an error. $ ruby test.rb
Traceback (most recent call last):
1: from test.rb:3:in `<main>'
test.rb:3:in `-': no implicit conversion of Hash into Array (TypeError) Can you reopen this issue, or should I open a new issue? By the way, is there a better way to write the above code? |
@RichardsonWTR can you make sure you're using the latest version of RuboCop and try again? If the problem persists, create a new ticket please. 🙌 |
Thanks @dvandersluis |
Testing using RuboCop commit 2d3e1bc
Input file:
Command
Changed file:
Running the code now results in:
The text was updated successfully, but these errors were encountered: