Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access array[3..last] (ruby)

Tags:

arrays

ruby

how can I access all array elements from x to the last one?

my_array= [1,2,3,4,5,6]
puts my_array[3..last]
like image 735
Radek Avatar asked Feb 18 '10 21:02

Radek


People also ask

How can you get the last item of an array Ruby?

Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

How do you access an array in Ruby?

Accessing Items in Arrays You access an item in a Ruby array by referring to the index of the item in square brackets. The sharks array has three elements. Here is a breakdown of how each element in the sharks array is indexed. The first element in the array is Hammerhead , which is indexed at 0 .

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


2 Answers

An index of -1 gives the last item in the array:

my_array[3..-1]

In fact, any negative index begins counting backwards from the end of the array.

Thanks to Peter for reminding me of the better way to do this.

like image 85
Aaron Avatar answered Sep 22 '22 01:09

Aaron


Use a negative index, as in my_array[3..-1].

my_array= [1,2,3,4,5,6]
puts my_array[3..-1]
=> [4, 5, 6]
like image 37
Peter Avatar answered Sep 25 '22 01:09

Peter