我试图打印出数组中的每一项及其位置。例如。
bear[0]
代码如下:
animals = ["bear", "ruby", "peacock", "kangaroo", "whale", "platypus"]
for i in animals
puts i
end
最佳答案
在 Ruby 中,使用 Enumerable
module 提供的方法是惯用的混入Array
class而不是使用传统的 for
循环:
animals.each_with_index { |x,i| puts "#{x}[#{i}]" } # => animals
# bear[0]
# ruby[1]
# peacock[2]
# kangaroo[3]
# whale[4]
# platypus[5]
PickAxe Book 在其有关 Blocks and Iterators 的部分中提到了这一点.
关于ruby - 如何打印数组的内容及其位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286397/