Skip to content
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

Add new Style/ArrayFirstLast cop #12416

Merged
merged 1 commit into from
Nov 28, 2023

Conversation

fatkodima
Copy link
Contributor

Fixes #12406.

I already implemented this cop (so that's why still decided to open a PR) when realised that .first/.last is only suited for arrays. While [0] and [-1] can be also used with strings or hashes. So this can probably generate many false positives. I made it disabled by default.

@bbatsov
Copy link
Collaborator

bbatsov commented Nov 27, 2023

If the methods are specific only to arrays, I guess we can name the cop "ArrayFirstLast" or something more generic like "ArrayElementAccess". Might be good to make this configurable for whoever prefers indices as well, although I don't feel strongly about this.

I made it disabled by default.

Makes sense.

@fatkodima fatkodima changed the title Add new Style/FirstLast cop Add new Style/ArrayFirstLast cop Nov 27, 2023
@fatkodima
Copy link
Contributor Author

Changed the name.

@koic
Copy link
Member

koic commented Nov 27, 2023

Documenting the reason for being disabled by default will help users understand.

@fatkodima
Copy link
Contributor Author

Added a line regarding why it is disabled.

# The cop is disabled by default due to safety concerns.
#
# @safety
# Autocorrection is unsafe because `[0]` or `[-1]` can be called on a Hash,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Not just the autocorrection is unsafe - the cop is fundamentally unsafe. :-)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure, copy paste error 🤦 😅

@bbatsov bbatsov merged commit af5b0d7 into rubocop:master Nov 28, 2023
29 checks passed
@fatkodima fatkodima deleted the style-first_last_cop branch November 28, 2023 08:57
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.

Cop idea: Prefer first and last over [0] and [-1]
3 participants