在Ruby中使用Array.fetch()方法访问Array的元素

我们以在Ruby中声明Array的方式而闻名,或者可以说我们如何创建Array类的实例。我们也知道Ruby有一个丰富的库,您可以在其中找到各种预定义的方法,并根据您的代码要求使用它们。在本教程中,我们将学习Ruby库的一种方法,即Array.fetch()方法。此方法用于从Array类的对象访问或获取特定元素。我们还将看到它与Array有何不同。at()方法?

通过使用 Array.fetch ()方法,您可以在特定的索引中找到任何元素。这种方法在大多数情况下都很有用。它不同于 Array.at ()方法,因为如果遍历或搜索超出界限,解释器会给出一个错误。如果你想遍历一个数组或者你可以说你想打印数组的每一个元素,那么你可以用下面的方法来处理,

 Array.fetch(index)

当您在代码中实现上述语法时,对您来说将更加清晰。让我们看看如何在代码中实现它?

范例1:

# 数组声明
Adc = ['Nhooo.com','Ruby','c++','C#','php']

# 输入索引/位置
puts "Enter the index of element you want to find"
inx = gets.chomp.to_i

# 访问元素并打印
puts "Element at index #{inx} is #{Adc.fetch(inx)}"

输出结果

RUN 1:
Enter the index of element you want to find 
2
Element at index 2 is c++

RUN 2:
Enter the index of element you want to find
 34
index 34 outside of array bounds: -5...5
(repl):9:in `fetch'
(repl):9:in `<main>'

说明:

您可以在上面的代码中找到我们试图在Array中打印的元素,该元素出现在用户输入的特定索引处。在运行1中,您可以看到,当用户输入正确的索引时,将获得该值;但是在运行2中,当用户输入了错误的索引或该索引大于Array的长度,然后解释器时会给你一个错误。

范例2:

# 数组声明
Adc = ['Nhooo.com','Ruby','c++','C#','java','python']

# 极限值 
puts "Enter the limit of traverse"
lm = gets.chomp.to_i

# 循环打印带有元素的索引
i = 0
for i in 0..lm
  puts "Element at index #{i} is #{Adc.fetch(i)}"
end

输出结果

RUN 2:
Enter the limit of traverse
 4
Element at index 0 is Nhooo.com
Element at index 1 is Ruby
Element at index 2 is c++
Element at index 3 is C#
Element at index 4 is java

RUN 2:
Enter the limit of traverse
 23
Element at index 0 is Nhooo.com
Element at index 1 is Ruby
Element at index 2 is c++
Element at index 3 is C#
Element at index 4 is java
Element at index 5 is python
index 6 outside of array bounds: -6...6
(repl):11:in `fetch'
(repl):11:in `block in <main>'
(repl):10:in `each'
(repl):10:in `<main>'

说明:

在上面的代码中,您可以观察到 Array.fetch ()方法也可以用来遍历 Array。在这里,我们从控制台以输入值的形式对用户进行限制,并根据用户的需求遍历 Array。在运行1中,执行顺利,因为限制小于 Array 的长度,但在运行2中,解释器出错,因为限制大于计数。这样,fetch ()就不同于 Array.at ()方法。