Ruby equivalent to Python "array [i:]" to select all array elements after i?

I believe I want something like Python

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

ALL the time these days.

The solution always ends with a multilayer and ugly one. I am wondering which of the most elegant solutions may be, because mine is not worth showing.

+8
arrays ruby
source share
2 answers

You can write:

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

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

The best alternative to Ruby is to use the Array#drop :

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

Use Array # drop

 2.1.0 :019 > ary.drop(2) => [3, 4, 5, 6, 7, 8] 
+14
source share

All Articles