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
.
array.first
array.first
does not take any parameters.
array.first
returns the first element of an array.
Note:
array.first
is not the same as thearray.first()
function, which returns the firstn
elements of an array.
In the example below, we create a simple array and make use of the .first
property.
# creating arrayslanguagesArray = ["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.