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

Example:

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

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

+65
arrays ruby
Dec 26 '11 at 23:05
source share
2 answers

Use index -1 (negative indices are counted back from the end of the array):

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

or Array#last :

 a.last # => 5 b.last # => 6 
+146
Dec 26 '11 at 23:07
source share

In another way, using the splat operator:

 *a, last = [1, 3, 4, 5] STDOUT: a: [1, 3, 4] last: 5 
+4
Sep 01 '15 at 10:37
source share



All Articles