Topic: Enumerable#each: first/last iteration

In Enumerable#each, how can I run some code only in first or last iteration?
I need class="first" in the first iteration and class="last" in last.

<% items.each do |item| %>
  <li class="...">...</li>
<% end %>

Thanks.

Last edited by zakjan (2010-01-13 13:15:58)

Re: Enumerable#each: first/last iteration

do something if items.first == item
do something if items.last == item

Re: Enumerable#each: first/last iteration

There's no 'nice' way to do this. What happens when you only have 1 item in the list? What class should it get?

Re: Enumerable#each: first/last iteration

I would say both classes in that case, as the default behaviour, since it *is* both first and last. If that causes any clashes in the styling, then thats when you worry about it, otherwise you might want it to have both first and last styles.

I'd do it like this:

<% items.each_with_index do |item,i| %>
  <li class="<%= 'first' if i == 0 %> <%= 'last' if i == (items.size - 1)%>">...</li>
<% end %>

if you want it to only have one or the other (with first over-riding last) then i'd do this. 

<% items.each_with_index do |item,i| %>
  <li class="<%=  case i ; when 0 then 'first'; when (items.size - 1) then 'last';end %>">...</li>
<%= end %>

here i've used a rather ugly and hard to read inline case statement, but it works anyway.  You could find other ways.

Last edited by Max Williams (2010-01-14 13:59:33)

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Enumerable#each: first/last iteration

specious wrote:

What happens when you only have 1 item in the list? What class should it get?

Definitely both.

<% @menu.each do |page| %>
  <%
    classes = []
    classes << "first"  if page == @menu.first
    classes << "last"   if page == @menu.last
    classes << "active" if current_page?(page)
  %>
  <li class="<%= classes.join(" ") %>"><%= link_to page.title, page %></li>
<% end %>

Last edited by zakjan (2010-01-14 22:49:28)

Re: Enumerable#each: first/last iteration

zakjan - this is a bit of a pedantic point, and it's probably not relevant here, but in your code if menu happens to have repeated pages in it then all the repetitions will get that style, whereas in my example it's guaranteed to only be the first and last.  I imagine that won't happen since the menu will always be a list of unique pages but just thought i'd mention it anyway.

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams