views:

77

answers:

3

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 %>
+1  A: 

Interesting question. Use an each_with_index.

len = @stuff.length

@stuff.each_with_index do |x, index|
  if index == len
    # do something
  end
end
Ahsan Ali
A: 

A somewhat naive way to handle it, but:

<% @stuff.each_with_index do |thing, i| %>
  <% if (i + 1) == @stuff.length %>
    ...
  <% else %>
    ...
  <% end %>
<% end %>
apostlion
A: 

A more lispy alternative is to be to use

@stuff[1..-1].each do |thing|

end
@stuff[-1].do_something_else
Sam