$-6ren">
gpt4 book ai didi

ruby - 在 Ruby 中迭代数组的 "right"方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:18 26 4
gpt4 key购买 nike

PHP,尽管有其缺点,但在这方面相当不错。数组和散列之间没有区别(也许我太天真了,但这对我来说显然是正确的),并且遍历任何一个你只是做

foreach (array/hash as $key => $value)

在 Ruby 中有很多方法可以做这种事:

array.length.times do |i|
end

array.each

array.each_index

for i in array

哈希更有意义,因为我总是使用

hash.each do |key, value|

为什么我不能对数组执行此操作?如果我只想记住一种方法,我想我可以使用 each_index (因为它使索引和值都可用),但不得不做 array[index] 很烦人而不仅仅是 value .


哦对了,我忘了 array.each_with_index .然而,这个很糟糕,因为它是|value, key|hash.each|key, value| !这不是疯了吗?

最佳答案

这将遍历所有元素:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

# Output:

1
2
3
4
5
6

这将遍历所有元素,为您提供值和索引:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

# Output:

A => 0
B => 1
C => 2

根据你的问题,我不太确定你要找的是哪一个。

关于ruby - 在 Ruby 中迭代数组的 "right"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/310634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com