2012-08-03 45 views
1

我想迭代一些字段名稱,將索引號附加到字段的名稱,例如claim_1claim_2claim_3查看字段的軌道迭代

簡化視圖:

<% (1..4).each_with_index do |index| %> 
    <%= f.label :claims_index %> 
<% end %> 

我怎樣才能獲得該指數是1,2,3,4分別或任何?

回答

1

其實你不需要each_with_index迭代器這一點 -

<% 1.upto(4) do |i| %> 
    <%= f.label "claims_#{i}" %> 
<% end %> 
+0

這似乎更簡潔 - 謝謝! – Harry 2012-08-03 12:48:10

1
<% (1..4).each_with_index do |index| %> 
    <%= f.label "claim_#{index}" %> 
<% end %> 
0

不知道這是否是你所追求,但each_with_index有兩個參數,所以你可以這樣做:

<% @claims.each_with_index do |claim,index| %> 
    <%= "#{index+1}: #{claim.name}" %> 
<% end %> 

這將打印出的每個要求名和索引(1,2,3 ,4)+1使得它基於1,而不是基於0。

Alteranatively,只需使用:

<% (1..4).each do |i| %> 
    <%= i %> 
<% end %>