Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.fetch() in Ruby?

okwudili onyejiaku

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 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}"

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 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.


Example 3

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

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring