0
<% 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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
May be that will be an issue... Please correct me according to need.
@Palani Have you tried taking first element from your collection? Just like above, collection[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.