Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine last object in each loop?

In your typical each loop in Rails, how do I determine the last object, because I want to do something different to it than the rest of the objects.

<% @stuff.each do |thing| %>  <% end %> 
like image 592
alamodey Avatar asked May 30 '09 06:05

alamodey


People also ask

How do you check the last element in foreach?

you can do a count(). or if you're looking for ONLY the last element, you can use end(). end(arr); returns only the last element.

How do you find the last element of a for loop?

Use Counter in PHP foreach Loop Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array.


1 Answers

@stuff.each do |s|   ...normal stuff...   if s == @stuff.last     ...special stuff...   end end 
like image 84
abject_error Avatar answered Sep 25 '22 02:09

abject_error