Reputation: 14938
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 %>
Upvotes: 41
Views: 34472
Reputation: 18491
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.
Upvotes: 1
Reputation: 2938
@stuff.each do |s|
...normal stuff...
if s == @stuff.last
...special stuff...
end
end
Upvotes: 67
Reputation: 981
<% @stuff[0...-1].each do |thing| %>
<%= thing %>
<% end %>
<%= @stuff.last %>
Upvotes: 8
Reputation: 749
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
Upvotes: 33
Reputation: 1014
A more lispy alternative is to be to use
@stuff[1..-1].each do |thing|
end
@stuff[-1].do_something_else
Upvotes: 2
Reputation: 720
A somewhat naive way to handle it, but:
<% @stuff.each_with_index do |thing, i| %>
<% if (i + 1) == @stuff.length %>
...
<% else %>
...
<% end %>
<% end %>
Upvotes: 2