array.fetch()
or fetch()
is a Ruby function that is used to find and return an element based on the index passed to the fetch()
function or method.
array.fetch([n])
n
: This is the index of the element to fetch.The element with the index position specified is returned.
In the example below, we create arrays and use the fetch()
method to find and return some of their elements.
# create arrays array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = ["Python", "Ruby", "Java"] array4 = [true, false, nil, 0, 1] # fetch some elements of arrays above a = array1.fetch(0) b = array2.fetch(4) c = array3.fetch(1) d = array4.fetch(3) # print values returned puts "#{a}" puts "#{b}" puts "#{c}" puts "#{d}"
Passing a negative index position means that counting starts from -1
and this is the last element in the array.
See the example below:
# create an array array = [1, 2, 3, 4, 5] # use the fetch() method a = array.fetch(-2) # fetch second element from the last b = array.fetch(200) # index out of bound # print value of element puts "#{a}" puts "#{b}"
Note that fetching an array by an index that is out of bounds results in an error.
See the example code below:
# create an array array = [1, 2, 3, 4, 5] # use the fetch() method a= array.fetch(200) # index out of bound # print value of element puts "#{a}" # throws an error
RELATED TAGS
CONTRIBUTOR
View all Courses