OneBite.Dev - Coding blog in a bite size

get the last element of array in Ruby

Code snippet on how to get the last element of array in Ruby

array[-1]

This code is a simple way to return the last element from an array in Ruby. The square brackets are used to access an element in the array, and the “-1” specifies to access the last one. For example, if you had an array called “my_array” which contained numbers 1-10 and wanted to access the last element, you could use this code: “my_array[-1]”, which would return the number 10. Since arrays are zero-indexed, “-1” is the same as selecting the 9th element, which would be the last one.

ruby