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)
at()
method. This represents the index of the element to search for.The value returned is the array element whose index position is passed to the at()
method.
nil
is returned if the index position passed to theat()
function is out of range.
Let’s see an example below. In this example, we created several arrays and accessed some of their elements using the at()
method.
# creat arrays arr1 = [1, 2, 3, 4,5] arr2 = ["a", "b", "c", "d", "e"] arr3 = ["Meta", "Amazon", "Google", "Netflix", "Apple"] # access array elements # with the `at()` method a = arr1.at(2) # 3rd position b = arr2.at(5) # 6th position c = arr3.at(0) # 1st postion # print out returned values puts a puts b puts 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.
RELATED TAGS
CONTRIBUTOR
View all Courses