Skip to content

Error in Rails/IndexWith when using nil #1463

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

Open
ydakuka opened this issue Mar 6, 2025 · 3 comments · May be fixed by #1470
Open

Error in Rails/IndexWith when using nil #1463

ydakuka opened this issue Mar 6, 2025 · 3 comments · May be fixed by #1470

Comments

@ydakuka
Copy link
Contributor

ydakuka commented Mar 6, 2025

Describe

I have code:

arr.to_h { |id| [id, 0] }

Then I run rubocop with autocorrect and get:

arr.index_with { |_id| 0 }

However:

arr = [1, 2, 3]
arr.to_h { |id| [id, 0] }  # => {1=>0, 2=>0, 3=>0}
arr.index_with { |_id| 0 } # => {1=>0, 2=>0, 3=>0}

arr = nil
arr.to_h { |id| [id, 0] }  # => {}
arr.index_with { |_id| 0 } # NoMethodError: undefined method `index_with' for nil:NilClass

RuboCop

$ rubocop -V
1.72.2 (using Parser 3.3.7.1, rubocop-ast 1.38.0, analyzing as Ruby 2.7, running on ruby 2.7.8) [x86_64-linux]
  - rubocop-capybara 2.21.0
  - rubocop-factory_bot 2.26.1
  - rubocop-performance 1.23.1
  - rubocop-rails 2.29.1
  - rubocop-rake 0.6.0
  - rubocop-rspec 3.4.0
  - rubocop-rspec_rails 2.30.0
  - rubocop-thread_safety 0.6.0
@ydakuka ydakuka changed the title Error with Rails/IndexWith when using nil Error in Rails/IndexWith when using nil Mar 6, 2025
@tejasbubane
Copy link
Contributor

tejasbubane commented Mar 26, 2025

This is an edgecase (nil#to_h). And rubocop cannot determine value the itself. I'm not sure if this case is enough reason to mark the cop as unsafe.

@ydakuka
Copy link
Contributor Author

ydakuka commented Mar 26, 2025

I'm not sure if this case is enough reason to mark the cop as unsafe.

This edge case leads to bugs, so it's unsafe.

tejasbubane added a commit to tejasbubane/rubocop-rails that referenced this issue Mar 26, 2025
@tejasbubane
Copy link
Contributor

Right I see Rails/Blank also marked unsafe due to receiver: https://github.com/rubocop/rubocop-rails/pull/445/files

@tejasbubane tejasbubane linked a pull request Mar 26, 2025 that will close this issue
9 tasks
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 a pull request may close this issue.

2 participants