Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 89ed244

Browse files
committed
Improve wording
1 parent 41b9ba4 commit 89ed244

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

README.adoc

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4554,11 +4554,13 @@ NOTE: You can read more about the rationale behind this guideline https://bugs.r
45544554

45554555
=== Slicing with Ranges
45564556

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`.
45584560

45594561
[source,ruby]
45604562
----
4561-
# bad
4563+
# bad - you're selecting all the elements of the array
45624564
ary[0..-1]
45634565
ary[0..nil]
45644566
ary[0...nil]
@@ -4567,29 +4569,28 @@ ary[0...nil]
45674569
ary
45684570
----
45694571

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.
45714573

45724574
[source,ruby]
45734575
----
4574-
# bad
4576+
# bad - hard to process mentally
45754577
ary[1..-1]
45764578
ary[1..nil]
45774579
4578-
# good
4580+
# good - easier to read and more concise
45794581
ary[1..]
45804582
----
45814583

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]`.
45864587

45874588
[source,ruby]
45884589
----
4589-
# bad
4590+
# bad - hard to process mentally
45904591
ary[nil..42]
45914592
4592-
# good
4593+
# good - easier to read
45934594
ary[..42]
45944595
ary[0..42]
45954596
----

0 commit comments

Comments
 (0)