2014-02-26 16 views
2

這應該相當簡單,我知道如何在迭代中增加計數器以及如何嵌套循環 - 但我想知道是否有更優雅的解決方案?如何迭代多個數組並在每次迭代後添加一個異常?

如何計算迭代運行的頻率,並在每次運行X次時注入其他代碼?

我試過使用each_slice,但是這是看數組本身的內容而不是數組的數量。

這裏是我的示例代碼:

<% @organization.users.each do |user| %> 
    <div class="row"> 
    <div class="col-xs-6 col-md-3"> 
    <%= user.profile.first_name %> <%= user.profile.last_name %> 
    <%= link_to 'Show', organization_user_path(@organization, user.id) %> 
    <%= link_to 'Edit', '#' %> 
    </div> 
    </div> 
<% end %> 

理想我想運行循環4次和第4次後,新的行會被添加

回答

2

您可以使用each_with_index並使用索引來知道電話號碼迴圈已經運行的次數

<% @organization.users.each_with_index do |user, i| %> 
    <div class="row"> 
    <div class="col-xs-6 col-md-3"> 
    <%= user.profile.first_name %> <%= user.profile.last_name %> 
    <%= link_to 'Show', organization_user_path(@organization, user.id) %> 
    <%= link_to 'Edit', '#' %> 
    </div> 
    </div> 
    <%if (i+1)%4 == 0 %> 
    <% end %> 
<% end %> 
+0

謝謝,這就像一個魅力工作! –

相關問題