loops – each_with_index desired column output Rails – Education Career Blog

<% source.strains.each_with_index do |strain, j| %>
 <% if (j == (source.strains.size - 1)) %>
  <font size="3">Strain <%= strain0.appendix %> </font>
 <% end %>                       
<% end %>

I need to get output as

If j value is last one of a loop, then i need to print first value of loop (j0). Kindly suggest me or correct above script.


Looks like your code is the same as

<font size="3">Strain <%= source.strains.last0.appendix %> </font>

(Without any loop)

Check out Array#last

But even if you didn’t know about last method, making a loop to access last element in collection is kinda weird. You can, at least, do collectioncollection.size - 1.

on comment
Then why’re you doing strain0 instead of source.strains0? source.strains is your collection and strain is just a current element in the loop. I thought strain is some kind of array too.

Leave a Comment