11

I find myself wanting something like Python's

ary = [1,2,3,4,5,6,7,8]
ary[2:] #=> [3,4,5,6,7,8]

ALL of the time these days.

The solution always ends up being multi-lined and ugly. I'm wondering what the most elegant solutions out there might be, because mine are not worth showing.

4
  • 1
    It's not much different: ary[2..-1]. Commented Mar 27, 2014 at 16:32
  • The -1 in a Range is somewhat ugly and magic when used in this context ( e.g. (2..-1).each doesn't match this behaviour). Commented Mar 27, 2014 at 16:35
  • If you want to keep the first n items, and can alter arr, you can use front = arr.shift(n). A less-desirable alternative to drop(n) is last(arr.size-n). Commented Mar 27, 2014 at 16:44
  • Note that Array#[] is a.k.a Array#slice: ary[2..-1] can be written ary.slice(2..-1). Commented Mar 27, 2014 at 18:36

2 Answers 2

15

Use Array#drop

2.1.0 :019 > ary.drop(2)
 => [3, 4, 5, 6, 7, 8] 
Sign up to request clarification or add additional context in comments.

2 Comments

This is the best answer. It works with all Enumerables and even lazy enumerators. To perform the opposite operation, there is the take(n) method. Also available are the drop_while and take_while methods.
Indeed.. It is best.. :)
11

You can write:

ary[2..-1]
# => [3,4,5,6,7,8]

-1 is the index of the last element in the array, see the doc for Array#[] for more informations.

A better alternative in Ruby is to use the Array#drop method:

ary.drop(2)
# => [3,4,5,6,7,8]

1 Comment

I used to use the #drop thing, but -1 symbolizing the last element in an array is ultimately the easiest way to remember how to do this and all sorts of other permutations of this sort of thing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.