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 54cbbb4
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4548,6 +4548,48 @@ obj.then { |x| x.do_something }

NOTE: You can read more about the rationale behind this guideline https://bugs.ruby-lang.org/issues/14594[here].

=== Slicing with Ranges

`[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]
----

== Numbers

=== Underscores in Numerics [[underscores-in-numerics]]
Expand Down

0 comments on commit 54cbbb4

Please sign in to comment.