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

Suggested cop: prefer first/drop/last over [] with particular kinds of ranges #220

Open
amomchilov opened this issue Apr 4, 2024 · 0 comments

Comments

@amomchilov
Copy link
Contributor

There's a bunch of overloads of #slice/#[], many of which are technically nilable, but don't return nil in practice.

We can't fix that in the general case, but of a lot uses with ranges start from 0 (or ending in -1 can be replaced by more dedicated methods like first/drop/last, which aren't nilable.

A challenge here is that the APIs aren't consistent between Array and String (and other types), and there's no way to only make the change for particular types.

These examples assume:

a = Array(0..9)
s = Array("a".."z").join

Replace with first

Applicable for Array, but requires a patch from ActiveSupport for String.

-T.must(s[0..5])
-T.must(s[ ..5])
+s.first(6)
-T.must(s[0...5])
-T.must(s[ ...5])
-T.must(s[0, 5])
+s.first(5)

Replace with last

Applicable for Array, but not to String.

-T.must(a[5..-1])
-T.must(a[5..  ])
-T.must(a[5... ])
+a.drop(5)

Replace with dup

Really, these likely just be s, but we can't be sure that the callers weren't relying on the result being a new copy of the string, so we'd conservatively need to dup it.

-T.must(s[0..])
-T.must(s[0...])
-T.must(s[..-1])
s.dup
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

No branches or pull requests

1 participant