有一个简单的问题。
我想放置数组的索引号,而不是数组索引的实际值。因此,如果array [0] = book1,我想放入0,而不是book1。我怎样才能做到这一点?
更具体地说,如果相关,在我的任务中,我要循环打印阵列中的每个专辑,但也想打印每个专辑的编号。
index = 0
while index < albums.length
print_album(albums[index])
index += 1
end
Run Code Online (Sandbox Code Playgroud)
Rubyists通常不会while在数组上进行迭代。惯用的语言是:
albums.each_with_index do |album, index|
puts "#{index}: #{album}"
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |