Ruby at() Method

Ruby at() Function with Examples

Ruby at() method is an array function that is used to pop an element from a targeted array also from a specified index. Since the index starts from 0. That is why the first element indicates the index of 0, the second element indicates the index of 1, and so on.

The elements can be eliminated from the end by specifying negative value at index. The negative values start from -1 and -1 indicates the end element of the input array, -2 indicates the last end element, and so on.

 Ruby at() Method

Syntaxarr.at(index)
Where arr is the targeted array and index is the index number of the input array for removing that element.
ParametersThe index number of the input array. at() method can take a maximum of 1 parameter.
Return ValueReturns the input element of the specified index.

Example program-1:

arr1 = [1, 2, 3, 4, 5, 6]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Mehrab", "Mohul", "Lina", "Lia"]

x = arr1.at(0)
y = arr2.at(1)
z = arr3.at(-2)
xy = arr3.at(-3)

puts "#{x}"
puts "#{y}"
puts "#{z}"
puts "#{xy}"

Output

1
b
Lina
Mohul

The at() method returns the element of an input array that is specified by the index number. And we can keep the return value in a variable like the above example. The data type is automatically mapped when the value is returned.

Example Program-2:

arr1 = [1, 2, 3, 4, 5, 6]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Mehrab", "Mohul", "Lina", "Lia"]

# directly locating elements
puts "#{arr1.at(0)}"
puts "#{arr2.at(2)}"
puts "#{arr3.at(-1)}"
puts "#{arr3.at(-3)}"

Output

1
c
Lia
Mohul
Posted in