Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Ruby | at() function

  • Last Updated : 06 May, 2019

The at() function in Ruby is used to return the element of the specified index. Index 0 is for the first element of the array, 1 for the second element of the array and so on. The negative index counts from the end of the input array.

Syntax: Array.at(Index)
Here Array is the input array of elements at which at() function is called.

Parameters:
Index : Its corresponding elements are to be returned and this index may be negative, positive or zero.

Returns: the corresponding elements whose index is taken as the parameter.

Example 1:






# Initialising a array of elements
Array = ["a", "b", "c", "d", "e", "gfg"
         "Geeks", "Geek", "GeeksforGeeks"]
   
# Calling to at() function
A = Array.at(0)
B = Array.at(1)
C = Array.at(3)
D = Array.at(5)
E = Array.at(-1)
F = Array.at(-3)
   
# Getting the corresponding elements 
# whose indexs are given as parameter
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"
puts "#{E}"
puts "#{F}"

Output:

a
b
d
gfg
GeeksforGeeks
Geeks

Example 2:




# Initializing a array of elements
Array = [0, 1, 2, 3, 4, 10, 20, 30, 40]
  
# Calling the at() function with indexes 
# as the parameter and getting the
# corresponding elements whose indexs are given
puts "#{Array.at(0)}"
puts "#{Array.at(1)}"
puts "#{Array.at(3)}"
puts "#{Array.at(5)}"
puts "#{Array.at(-1)}"
puts "#{Array.at(-3)}"

Output:

0
1
3
10
40
20

Reference: https://devdocs.io/ruby~2.5/array#method-i-at




My Personal Notes arrow_drop_up
Recommended Articles
Page :