ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

Prefer `drop` over `slice` (or `shift`) to retrieve all but the first array element

Open andyw8 opened this issue 5 years ago • 4 comments

A good argument here by @JoelQ:

https://github.com/thoughtbot/til/blob/master/ruby/all-but-the-first-element-from-array.md

https://ruby-doc.org/core-2.7.0/Array.html#method-i-drop

andyw8 avatar Feb 27 '20 02:02 andyw8

drop/take should definitely be used more often.

WDYT of

Use take to get the first few elements of an Array

# bad
cards[0..2]
cards[0, 3]
cards.slice(0..3)

# good
cards.take(3)

Use drop to get the last few elements of an Array (if you know how many you should skip, not how many you want to get!)

# bad
cards[3, -1]
cards[3..-1]
cards.slice(3..-1)

# good
cards.drop(3)

pirj avatar Feb 23 '21 18:02 pirj

I strongly disagree.

  1. Array#take has no reason to exist whatsover. Use Array#first(n) (or array[...n]).

  2. I never use Array#drop. Needing it is less frequent anyways, but if I need it, I'll prefer using array[2...], or deconstructing:

_reason_I_dont_want_this, _why_I_ignore_this_one_too, *what_I_want = array

take is a historical mistake and drop should not have been created either imo (not useful enough to warrant the cognitive load). I find the name to be unclear as it suggests a mutation.

In short I favor the contrary recommendation: always avoid take and drop 😅

marcandre avatar Feb 23 '21 19:02 marcandre

Considering that nil.to_a is a [], Array#[]'s disadvantage is not that critical.

pirj avatar Feb 23 '21 21:02 pirj

To add to this discussion, drop and take are not implemented for String, while slice and [] are.

pirj avatar Mar 22 '21 18:03 pirj