Skip to content

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

Description

@amomchilov

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp-wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions