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
Surprised this is not listed as an answer, but to my this is the cleanest way to do it. By starting the index at 1, you can remove the math of making the index and size match up.
@stuff = [:first, :second, :last]
@stuff.each.with_index(1) do |item, index|
if index == @stuff.size
# last item
else
# other items
end
end
also the added benefit here is that you can use this on the .map
as well.