The at()
method of the Array
class in Ruby returns an element from an Array
instance based on a specified index.
array.at(index)
# where array is any Array instance
index
: The index position of the element to search for.
The at()
method returns the element at the specified index
. at()
returns nil
if index
is out of range.
In the code below, we create array instances and extract some elements from the arrays with the at()
method. The extracted elements are printed to the console.
# creating array instances array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = ["Javascript", "Python", "Java", "C++", "Ruby"] array4 = ["cat", "dog", "elephant", "whale"] # search elements with "at()" method a = array1.at(2) b = array2.at(3) c = array3.at(1) # print returned values puts "#{array1}.at(2) returns #{a}" puts "#{array2}.at(3) returns #{b}" puts "#{array3}.at(1) returns #{c}"
When index
is out of range, a nil
value is returned, as shown below:
# create array array = [1, 2, 3, 4, 5] # search for element with "at()" method element = array.at(10) # index out of range. Returns nothing or nil # print returned value puts element
If a negative value for index
is specified, counting starts from the end, as shown below:
# create array array = ["a", "b", "c", "d", "e"] # search with "at()" method element = array.at(-3) # negative index # print element returned puts element
RELATED TAGS
CONTRIBUTOR
View all Courses