Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Ruby—如何打印数组的实际索引号,而不是该索引的值_Arrays_Ruby - Fatal编程技术网

Arrays Ruby—如何打印数组的实际索引号,而不是该索引的值

Arrays Ruby—如何打印数组的实际索引号,而不是该索引的值,arrays,ruby,Arrays,Ruby,我有一个简单的问题 我想输入数组的索引号,而不是数组索引的实际值。所以如果数组[0]=book1,我想放0,而不是book1。我该怎么做 更具体地说,如果相关的话,在我的任务中,我在循环中打印数组中的每个相册,但也要打印每个相册的编号 index=0 而索引

我有一个简单的问题

我想输入数组的索引号,而不是数组索引的实际值。所以如果数组[0]=book1,我想放0,而不是book1。我该怎么做

更具体地说,如果相关的话,在我的任务中,我在循环中打印数组中的每个相册,但也要打印每个相册的编号

index=0
而索引
Rubyists通常不会在迭代数组时使用
。您想要的内容按惯用方式写如下:

albums.each_with_index do |album, index|
  puts "#{index}: #{album}"
end

Ruby开发者通常不会使用
而使用
对数组进行迭代。您想要的内容按惯用方式写如下:

albums.each_with_index do |album, index|
  puts "#{index}: #{album}"
end

嗯,Amadan的答案绝对正确——这就是你应该用Ruby做的。使用可枚举项更为惯用

index = 0
while index < albums.length
    puts "#{index} : #{albums[index]}"
    index += 1
end
index=0
而索引

是如何使用while循环实现的

嗯,Amadan的答案是绝对正确的——在Ruby中应该这样做。使用可枚举项更为惯用

index = 0
while index < albums.length
    puts "#{index} : #{albums[index]}"
    index += 1
end
index=0
而索引

是如何使用while循环实现的

我很感激你的回答,但我想在我的任务中使用这样的while循环,有什么方法可以用我的循环来实现吗?你的代码很好,只是不惯用。但是,打印隐藏在
print\u album
中,它显然只接受相册本身。您已经有了可以打印的变量
索引
。要么只是。。。打印它,或修改
print\u album
以执行此操作(并接受索引参数)。我感谢您的回答,但我打算在我的任务中使用类似的while循环,是否有任何方法可以使用我的循环?您的代码很好,只是不惯用。但是,打印隐藏在
print\u album
中,它显然只接受相册本身。您已经有了可以打印的变量
索引
。要么只是。。。打印它,或修改
print\u album
以执行此操作(并接受index参数)