如何在 Ruby 中访问数组元素
在本文中,我们将学习如何在 Ruby 中访问数组元素。
在 Ruby 中,有几种方法可以从数组中检索元素。 Ruby 数组提供了许多不同的方法来访问数组元素。但最常用的方法是使用数组的索引。
使用索引 –
# Ruby program to demonstrate the
# accessing the elements of the array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
# accessing array elements
# using index
puts str[1]
# using the negative index
puts str[-1]
输出:
G4G
Geeks
从数组中检索多个元素:
有时,我们需要访问数组中的多个元素。因此要访问多个元素,请将两个指定的数组索引传递到 [] 中。
# Ruby program to demonstrate the
# accessing the multiple elements
# from array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
# accessing multiple array elements
puts str[2, 3]
输出:
Sudo
Geeks
对于多维数组
# Ruby program to demonstrate the
# accessing the multiple elements
# from array
# creating string using []
str = [["GFG", "G4G", "Sudo"],
[ "Geeks", "for", "portal"] ]
# accessing item from multi-array
puts str[1][2]
输出:
portal