Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

How to access array with array.at() in Ruby

okwudili onyejiaku

Overview

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)

Parameter

  • array: This is the array whose element we want to access.
  • index: This is an integer value we pass to the at() method. This represents the index of the element to search for.

Return value

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 the at() function is out of range.

Code example

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

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring