📜  红宝石 | at()函数

📅  最后修改于: 2022-05-13 01:55:20.471000             🧑  作者: Mango

红宝石 | at()函数

Ruby 中的 at()函数用于返回指定索引的元素。索引 0 表示数组的第一个元素,1 表示数组的第二个元素,依此类推。负索引从输入数组的末尾开始计数。

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

输出:

a
b
d
gfg
GeeksforGeeks
Geeks

示例 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)}"

输出:

0
1
3
10
40
20

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