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 %>
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 %>
Interesting question. Use an each_with_index.
len = @stuff.length
@stuff.each_with_index do |x, index|
if index == len
# do something
end
end
A somewhat naive way to handle it, but:
<% @stuff.each_with_index do |thing, i| %>
<% if (i + 1) == @stuff.length %>
...
<% else %>
...
<% end %>
<% end %>
A more lispy alternative is to be to use
@stuff[1..-1].each do |thing|
end
@stuff[-1].do_something_else