我想也許你誤解each_with_index
。
each
將遍歷元件以陣列
[:a, :b, :c].each do |object|
puts object
end
其輸出;
:a
:b
:c
each_with_index
迭代的元件,並且也通過在索引(從零開始)
[:a, :b, :c].each_with_index do |object, index|
puts "#{object} at index #{index}"
end
其輸出
:a at index 0
:b at index 1
:c at index 2
如果希望則1索引只需添加1.
[:a, :b, :c].each_with_index do |object, index|
indexplusone = index + 1
puts "#{object} at index #{indexplusone}"
end
,輸出
:a at index 1
:b at index 2
:c at index 3
,如果你想遍歷數組的一個子集,那麼就選擇子集,然後遍歷它
without_first_element = array[1..-1]
without_first_element.each do |object|
...
end
陣列的第一索引總是要'0'。 – Kyle
該索引始終爲零。爲什麼這有關係? –
@Codejoy - 由於您的問題已被多個用戶解答,因此您可以點贊/接受一些答案。 – Kyle