views:

14

answers:

1
<% source.strains.each_with_index do |strain, j| %>
 <% if (j == (source.strains.size - 1)) %>
  <font size="3">Strain <%= strain[0].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 (j[0]). Kindly suggest me or correct above script.

+1  A: 

Looks like your code is the same as

<font size="3">Strain <%= source.strains.last[0].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 collection[collection.size - 1].

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

Nikita Rybak
@Nikita: I dont need to print last one. "last" will be used for printing last one. I need to print first element if last element occurs.
Palani Kannan
@Nikita: May be that will be an issue... Please correct me according to need.
Palani Kannan
@Palani Have you tried **taking first element from your collection**? Just like above, _collection[0]_.
Nikita Rybak
U are 100% correct... Its working great. Thanks lot.
Palani Kannan