ruby-style-guide
ruby-style-guide copied to clipboard
Prefer `drop` over `slice` (or `shift`) to retrieve all but the first array element
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
drop/take should definitely be used more often.
WDYT of
Use
taketo get the first few elements of an Array
# bad
cards[0..2]
cards[0, 3]
cards.slice(0..3)
# good
cards.take(3)
Use
dropto 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)
I strongly disagree.
-
Array#takehas no reason to exist whatsover. UseArray#first(n)(orarray[...n]). -
I never use
Array#drop. Needing it is less frequent anyways, but if I need it, I'll prefer usingarray[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 😅
Considering that nil.to_a is a [], Array#[]'s disadvantage is not that critical.
To add to this discussion, drop and take are not implemented for String, while slice and [] are.