2012-05-30 53 views
1

如何指定在使用紅寶石1.8.7集合上使用each_with_index時從哪個索引開始?Ruby 1.8.7 each_with_index索引偏移量

collection.each_with_index do |element, index = 1| 
    #do smth 
end 

使用它,這樣提供了以下錯誤:

syntax error, unexpected '=', expecting '|' 
collection.each_with_index do |element, i = 1| 

回答

2

試試這個:

collection[4..-1].each_with_index do |element, index| 
    #do smth 
end 

這個例子將從第五元素開始。

+0

那麼,那不是我所需要的。我需要索引以'1'開頭,'index'在塊中進一步使用。 – RomanKapitonov

+0

我理解正確嗎?例如,你有數組['a','b','c','d']。你想從元素'b'開始?或者你想要例如1的第一個索引不是0? – alexkv

+1

我想作者只需要'method_that_uses_index(index + 1)':) – jdoe