Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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.

like image 222
boulder_ruby Avatar asked Mar 27 '14 16:03

boulder_ruby


Video Answer


2 Answers

Use Array#drop

2.1.0 :019 > ary.drop(2)
 => [3, 4, 5, 6, 7, 8] 
like image 123
Kirti Thorat Avatar answered Oct 24 '22 03:10

Kirti Thorat


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]
like image 10
toro2k Avatar answered Oct 24 '22 03:10

toro2k