【问题标题】:How can I iterate over multiple arrays and add an exception after every nth iteration?如何迭代多个数组并在每 n 次迭代后添加一个异常?
【发布时间】:2014-02-26 19:25:14
【问题描述】:

这应该相当简单,而且我知道如何在迭代中增加计数器以及如何嵌套循环 - 但我想知道是否有更优雅的解决方案?

如何计算迭代运行的频率并在每次运行 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 次之后添加一个新行

【问题讨论】:

    标签: ruby-on-rails ruby arrays loops


    【解决方案1】:

    您可以使用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 %>
    

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多