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.
Enumerableand sinceArrayinherits from it, the method is still available toArray.