Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is array.last in Ruby?

okwudili onyejiaku

The .last property of an array in Ruby returns the last element of the array.

The array.last property is not the same as the array.last() function. The array.last() function returns the last n elements from the array.

In Ruby, arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, and other Array objects.

An example of a Ruby array is shown below.

array= [ "a", "b", "c", "d", "e"]


The syntax of the .last property is as follows:


arrayinstance can be any instance of the Array class.

Return value

The .last property returns the last element of an array. If the array is empty, nothing will be returned.


In the code below, we will use the array.last property to access elements.

# creating arrays
languagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]
numbersArray = [1, 2, 3, 4, 5]
alphabetsArray = ["a", "b", "c", "d", "e"]

# Printing value to console
puts "#{languagesArray.last}" # Prints "Ruby on Rails"
puts "#{numbersArray.last}"   # Prints "5"
puts "#{alphabetsArray.last}" # Prints "e"

In the output above, the last element of each array is returned and displayed. When an array is empty and we access the .last property, nothing is returned, as shown below.

# create an empty array
emptyArray = []

puts "#{emptyArray.last}"    # Prints nothing because it is an empty array



View all Courses

Keep Exploring