Skip to content

Commit

Permalink
Add "Slicing with Ranges" rule
Browse files Browse the repository at this point in the history
Follow up rubocop/rubocop#12594 (comment).

This PR adds "Slicing with Ranges" rule.
  • Loading branch information
koic committed Jan 12, 2024
1 parent 5dcdd37 commit 92ee764
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -5273,6 +5273,50 @@ words.sub(/f/, 'f' => 'F') # => 'Foo bar'
words.gsub(/\w+/) { |word| word.capitalize } # => 'Foo Bar'
----

== Ranges

=== Slicing with Range

`[0..-1]` in `ary[0..-1]` is redundant and simply synonymous with `ary`.

[source,ruby]
----
# bad
ary[0..-1]
ary[0..nil]
ary[0...nil]
# good
ary
----

Ruby 2.6 introduced endless ranges.

[source,ruby]
----
# bad
ary[1..-1]
ary[1..nil]
# good
ary[1..]
----

Ruby 2.7 introduced beginless ranges. But, unlike the somewhat obscure `-1` in `ary[1..-1]`, the `0` in `ary[0..42]` is clear
as a starting point. In fact, changing it to `ary[..42]` could potentially make it less readable. Therefore, `ary[0..42]`
should respect the original programmer's intent. On the other hand, `ary[nil..42]` could be replaced with `ary[..42]`.
Similarly, `ary[1..nil]` could be replaced with `ary[1..]`.

[source,ruby]
----
# bad
ary[nil..42]
# good
ary[..42]
ary[0..42]
----

== Percent Literals

=== `%q` shorthand [[percent-q-shorthand]]
Expand Down

0 comments on commit 92ee764

Please sign in to comment.