2013-01-17 35 views
11

我在Rails應用程序中使用Ruby的迭代器在視圖上,像這樣:each_with_index_do從1開始的索引

<% ([email protected]).each_with_index do |element, index| %> 
    ... 
<% end %> 

我想到了另外的1 ..而不是隻說: @document.data

會得到上面的索引從1開始的技巧。但是,上面的代碼索引仍然是0到data.length(-1有效)。所以我做錯了什麼,我需要索引等於1-data.length ...不知道如何設置迭代器來做到這一點。

+0

陣列的第一索引總是要'0'。 – Kyle

+0

該索引始終爲零。爲什麼這有關係? –

+0

@Codejoy - 由於您的問題已被多個用戶解答,因此您可以點贊/接受一些答案。 – Kyle

回答

19

我想也許你誤解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

好吧,我意識到我的方式的錯誤。 – Codejoy

+0

不用擔心@Codejoy –

2

有沒有這樣的事情索引從1開始。如果你想跳過陣列中的第一項使用next

<% ([email protected]).each_with_index do |element, index| %> 
    next if index == 0 
<% end %> 
+1

瑣事:Perl有一個全局變量''['''您可以設置爲使所有數組索引從1開始或其他任何值。我們應該非常高興Ruby沒有這個。 –

2

數組索引始終爲零。

如果你想跳過第一個元素,它聽起來像你這樣做:

@document.data[1..-1].each do |data| 
    ... 
end 
1

如果我理解你的問題吧,你想從1開始索引,但在紅寶石數組作爲0基指標,所以最簡單的方法將是

給出@document.data是一個數組

index = 1 
@document.data.each do |element| 
    #your code 
    index += 1 
end 

HTH

+0

有史以來最酷的事情,但它的工作感謝 – MZaragoza

42

除非你使用的是老式的Ruby像1.8(我認爲這是在1中添加。9,但我不知道),你可以用each.with_index(1)獲得基於1枚舉:

在你的情況下,它會是這樣:

<% @document.data.length.each.with_index(1) do |element, index| %> 
    ... 
<% end %> 

希望幫助!

+3

當然這些日子更好的答案。 –

0

我有同樣的問題,並通過使用each_with_index方法解決它。但在代碼中的索引中添加1。

@someobject.each_with_index do |e, index| 
    = index+1 
1

使用Integer#next

[:a, :b, :c].each_with_index do |value, index| 
    puts "value: #{value} has index: #{index.next}" 
end 

生產:

value: a has index: 1 
value: b has index: 2 
value: c has index: 3