What is array.fetch() in Ruby?
Overview
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.
Syntax
array.fetch([n])
Parameters
n: This is the index of the element to fetch.
Return value
The element with the index position specified is returned.
Code
Example 1
In the example below, we create arrays and use the fetch() method to find and return some of their elements.
# create arraysarray1 = [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 abovea = array1.fetch(0)b = array2.fetch(4)c = array3.fetch(1)d = array4.fetch(3)# print values returnedputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"
Example 2
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 arrayarray = [1, 2, 3, 4, 5]# use the fetch() methoda = array.fetch(-2) # fetch second element from the lastb = array.fetch(200) # index out of bound# print value of elementputs "#{a}"puts "#{b}"
Note that fetching an array by an index that is out of bounds results in an error.
Example 3
See the example code below:
# create an arrayarray = [1, 2, 3, 4, 5]# use the fetch() methoda= array.fetch(200) # index out of bound# print value of elementputs "#{a}" # throws an error