在你典型的Rails每個循環中,我如何確定最後一個對象,因爲我想做一些與其他對象不同的東西。如何確定每個循環中的最後一個對象?
<% @stuff.each do |thing| %>
<% end %>
在你典型的Rails每個循環中,我如何確定最後一個對象,因爲我想做一些與其他對象不同的東西。如何確定每個循環中的最後一個對象?
<% @stuff.each do |thing| %>
<% end %>
有趣的問題。使用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.each_with_index do |thing, i| %>
<% if (i + 1) == @stuff.length %>
...
<% else %>
...
<% end %>
<% end %>
更lispy另一個方法是使用
@stuff[1..-1].each do |thing|
end
@stuff[-1].do_something_else
<% @stuff[0...-1].each do |thing| %>
<%= thing %>
<% end %>
<%= @stuff.last %>
@stuff.each do |s|
...normal stuff...
if s == @stuff.last
...special stuff...
end
end
我找到`如果指數== len + 1`更美觀。 – 2015-04-12 04:11:34
是不是假設是@ stuff.each_with_index do | index,x |? (首先是對象,然後是索引) – 2016-02-01 10:50:11
@BenjaminBenoudis將會是'if index == len-1' – andreofthecape 2016-10-28 06:45:24