Topic: Loop with different behavior for last item?

I am trying to loop through a group of objects in my RHTML and display their names/links plus a separator. But I don't want a separator after the last one. Is there a clean way to do this with Ruby? (I changed this from RHTML to Ruby for this code snippet):

for crumb in @breadcrumbs
  puts crumb.name
  puts " - " # separator
end

That gives me: Mike - Bob - Steve - Joe -

What I want is: Mike - Bob - Steve - Joe

Thanks!

Re: Loop with different behavior for last item?

It's better to use "join" like this:

<%= @breadcrumbs.map(&:name).join(' - ') %>

In this case there's no loop necessary. The map(&:name) part just returns a new array with all the names in it.

Railscasts - Free Ruby on Rails Screencasts

Re: Loop with different behavior for last item?

I like that method. However, I over simplified my example. I have some other code that runs in that loop as well, and each crumb is actually a hyperlink. Can that join be applied to a block of other code?

<% for crumb in @breadcrumbs %>
<%= '<i>' if crumb.italicize? -%>
<%= link_to crumb.name, :action => :show, :id => crumb -%>
<%= '</i>' if crumb.italicize? %>
&mdash;
<% end %>

Re: Loop with different behavior for last item?

I see. In that case you could do this.

<%= "&mdash;" unless crumb == @breadcrumbs.last %>

However, you may want to move this all into a helper methods:

<%= display_breadcrumbs(@breadcrumbs) %>

# in helper module
def display_breadcrumbs(breadcrumbs)
  breadcrumb_links(breadcrumbs).join(' &mdash; ')
end

def breadcrumb_links(breadcrumbs)
  breadcrumbs.collect do |crumb|
    if crumb.italicize?
      content_tag :i, crumb_link(crumb)
    else
      crumb_link(crumb)
    end
  end
end

def crumb_link(crumb)
  link_to crumb.name, :action => :show, :id => crumb
end


That's quite a bit more code, but in a sense I think it's cleaner.

Railscasts - Free Ruby on Rails Screencasts

Re: Loop with different behavior for last item?

Thanks Ryan. That unless crumb == @breadcrumbs.last was what I needed. Using a helper is a good idea. My RHTML was getting cluttered.