Search code examples
rubyruby-on-rails-3.2enumerable

Total Enumeration with Groupings


The following view establishes a grid of grouped items. The goal is to give the enumerated item overall not by grouping

<% biz.documents.in_groups_of(5).each do |documents| %>
  <div class="row">
    <div class="small-2 columns">&nbsp;</div>
    <% documents.each_with_index do |document, index| %>
      <div class="small-2 columns text-center">
        <% if document %>
          <i>Item <%= index + 1 %></i>

Practically: given groupings of 5, if there are 7 items, the output ends-up being

index 1 index 2 index 3 index 4 index 5  
index 1 index 2  

Is there a way to get an enum of each grouping so that it can multiply itself by the grouping factor and be added to the index?


Solution

  • You can use each_with_index in your grouped, outer loop as well. Try this:

    <% biz.documents.in_groups_of(5).each_with_index do |documents, group_index| %>
      <div class="row">
        <div class="small-2 columns">&nbsp;</div>
        <% documents.each_with_index do |document, index| %>
          <div class="small-2 columns text-center">
            <% if document %>
              <i>Item <%= (group_index * 5) + index + 1 %></i>
    

    It should produce the result you are looking for.