What is array.last in Ruby?
The .last property of an array in Ruby returns the last element of the array.
The
array.lastproperty is not the same as thearray.last()function. Thearray.last()function returns the lastnelements 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"]
Syntax
The syntax of the .last property is as follows:
arrayinstance.last
arrayinstancecan be any instance of theArrayclass.
Return value
The .last property returns the last element of an array. If the array is empty, nothing will be returned.
Code
In the code below, we will use the array.last property to access elements.
# creating arrayslanguagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]numbersArray = [1, 2, 3, 4, 5]alphabetsArray = ["a", "b", "c", "d", "e"]# Printing value to consoleputs "#{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 arrayemptyArray = []puts "#{emptyArray.last}" # Prints nothing because it is an empty array