What is array.first in Ruby?

Ruby arrays are a key foundation of programming in Ruby. They are used frequently, so it is useful to know and understand the most commonly used methods.

An example of an array is shown below.

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

array.first is a property of an array in Ruby that returns the first element of an array. If the array is empty, it returns nil. array.first accesses the first element of the array, i.e., the element at index 0.

Syntax

array.first

Parameters

array.first does not take any parameters.

Return value

array.first returns the first element of an array.

Note: array.first is not the same as the array.first() function, which returns the first n elements of an array.

Code

In the example below, we create a simple array and make use of the .first property.

# creating arrays
languagesArray = ["Ruby on Rails!", "Java", "C++", "Python", "Javascript" ]
numbersArray = [1, 2, 3, 4, 5]
emptyArray = []
puts "#{languagesArray.first}"
puts "#{numbersArray.first}"
puts "#{emptyArray.first}" # Prints nil because it is an empty array

In the code above, the emptyArray.first value is printed as nothing because does not contain any elements.

Free Resources