Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
andyw8 opened this issue Feb 27, 2020 · 4 comments
Labels

Comments

@andyw8
Copy link
Contributor

andyw8 commented Feb 27, 2020

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

@pirj
Copy link
Member

pirj commented Feb 23, 2021

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)

@marcandre
Copy link
Contributor

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 😅

@pirj
Copy link
Member

pirj commented Feb 23, 2021

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

@pirj
Copy link
Member

pirj commented Mar 22, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants