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]
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 .
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 .
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With