How to access array with array.at() in Ruby
Overview
The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element.
This element is the one in which the index position is the value passed in.
array.at(index)
Parameter
- array: This is the array whose element we want to access.
- index: This is an integer value we pass to the
at()method. This represents the index of the element to search for.
Return value
The value returned is the array element whose index position is passed to the at() method.
nilis returned if the index position passed to theat()function is out of range.
Code example
Let’s see an example below. In this example, we created several arrays and accessed some of their elements using the at() method.
# creat arraysarr1 = [1, 2, 3, 4,5]arr2 = ["a", "b", "c", "d", "e"]arr3 = ["Meta", "Amazon", "Google", "Netflix", "Apple"]# access array elements# with the `at()` methoda = arr1.at(2) # 3rd positionb = arr2.at(5) # 6th positionc = arr3.at(0) # 1st postion# print out returned valuesputs aputs bputs c
In the code above, the elements were found using the at() method except for line 14, where nothing is printed. This happened because the value passed to the at() function is out of range.