Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last element of an array in Ruby?

Tags:

arrays

ruby

Example:

a = [1, 3, 4, 5] b = [2, 3, 1, 5, 6] 

How do I get the last value 5 in array a or last value 6 in array b without using a[3] and b[4]?

like image 421
Rails beginner Avatar asked Dec 26 '11 23:12

Rails beginner


People also ask

How do you find the last element of an array in 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 .

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

How do you remove the last element of an array in Ruby?

The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.


1 Answers

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5 b[-1] # => 6 

or Array#last method:

a.last # => 5 b.last # => 6 
like image 138
KL-7 Avatar answered Sep 28 '22 06:09

KL-7