简体   繁体   中英

Determine index of element in Array.each

I'm trying to render a bulk of content in rows of three. However, I'm not sure how would I determine the current position of the element using Ruby. This is what I have:

<% Animals.each do | animal | %>
    <%= animal.species %>
<% end %>

I want to be able to add a <BR> or if I was rendering a table a </TR><TR> each time we'd hit the third animal in the set. Of course, if the number of elements nE isn't divisible by three, then the table would be malformed. I figured by doing a bit of checking after the iteration that I could close it.

But is there a way to get the index of an element that's being iterated over in an Array.each method? I have the strong hunch that I could just do the following:

<table>
<% Animals.each do | animal | %>
<% if Animals.find_index(animal) / 3 == 0 %>
   <tr>
<% end %>
       <td><%= animal.species %></td>
<% if Animals.find_index(animal) / 3 == 2 %>
   </tr>
<% end %>
</table>

My only thing is that Animal is a subclass of ActiveRecord::Base , so I'm not sure (haven't looked to see) if this would scale well, let alone if each call to find_index would be a super intensive method. Any suggestions are welcome.

You need

<% animals = Animals.all %>
<table>
<% animals.in_groups_of(3) do |animal_row| %>
  <tr>
    <% animal_row.compact.each do |animal| %>
      <td><%= render animal %></td>
    <% end %>
  </tr>
<% end %>
</table>

Should roughly do the job.

More importantly, I think keeping the Enumerable module's documentation handy has been great for me as a Ruby developer. It is my "favourite" module, and nearly ALWAYS helps me solve tricky problems easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM