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 %>
@stuff.each do |s|
...normal stuff...
if s == @stuff.last
...special stuff...
end
end
Interesting question. Use an each_with_index.
len = @stuff.length
@stuff.each_with_index do |x, index|
# should be index + 1
if index+1 == len
# do something
end
end
<% @stuff[0...-1].each do |thing| %>
<%= thing %>
<% end %>
<%= @stuff.last %>
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