You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.adoc
+12-11Lines changed: 12 additions & 11 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4554,11 +4554,13 @@ NOTE: You can read more about the rationale behind this guideline https://bugs.r
4554
4554
4555
4555
=== Slicing with Ranges
4556
4556
4557
-
`[0..-1]` in `ary[0..-1]` is redundant and simply synonymous with `ary`.
4557
+
Slicing arrays with ranges to extract some of their elements (e.g `ary[2..5]`) is a popular technique. Below you'll find a few small considerations to keep in mind when using it.
4558
+
4559
+
* `[0..-1]` in `ary[0..-1]` is redundant and simply synonymous with `ary`.
4558
4560
4559
4561
[source,ruby]
4560
4562
----
4561
-
# bad
4563
+
# bad - you're selecting all the elements of the array
4562
4564
ary[0..-1]
4563
4565
ary[0..nil]
4564
4566
ary[0...nil]
@@ -4567,29 +4569,28 @@ ary[0...nil]
4567
4569
ary
4568
4570
----
4569
4571
4570
-
Ruby 2.6 introduced endless ranges.
4572
+
* Ruby 2.6 introduced endless ranges, which provide an easier way to describe a slice going all the way to the end of an array.
4571
4573
4572
4574
[source,ruby]
4573
4575
----
4574
-
# bad
4576
+
# bad - hard to process mentally
4575
4577
ary[1..-1]
4576
4578
ary[1..nil]
4577
4579
4578
-
# good
4580
+
# good - easier to read and more concise
4579
4581
ary[1..]
4580
4582
----
4581
4583
4582
-
Ruby 2.7 introduced beginless ranges. But, unlike the somewhat obscure `-1` in `ary[1..-1]`, the `0` in `ary[0..42]` is clear
4583
-
as a starting point. In fact, changing it to `ary[..42]` could potentially make it less readable. Therefore, `ary[0..42]`
4584
-
should respect the original programmer's intent. On the other hand, `ary[nil..42]` could be replaced with `ary[..42]`.
4585
-
Similarly, `ary[1..nil]` could be replaced with `ary[1..]`.
4584
+
* Ruby 2.7 introduced beginless ranges, which are also handy in slicing. However, unlike the somewhat obscure `-1` in `ary[1..-1]`, the `0` in `ary[0..42]` is clear
4585
+
as a starting point. In fact, changing it to `ary[..42]` could potentially make it less readable. Therefore, using code like `ary[0..42]`
4586
+
is fine. On the other hand, `ary[nil..42]` should be replaced with `ary[..42]` or `arr[0..42]`.
0 commit comments