2009-05-30 61 views

回答

26

有趣的問題。使用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 
+1

我找到`如果指數== len + 1`更美觀。 – 2015-04-12 04:11:34

+0

是不是假設是@ stuff.each_with_index do | index,x |? (首先是對象,然後是索引) – 2016-02-01 10:50:11

+2

@BenjaminBenoudis將會是'if index == len-1' – andreofthecape 2016-10-28 06:45:24

2

一個有點天真的方法來處理它,但:

<% @stuff.each_with_index do |thing, i| %> 
    <% if (i + 1) == @stuff.length %> 
    ... 
    <% else %> 
    ... 
    <% end %> 
<% end %> 
1

更lispy另一個方法是使用

@stuff[1..-1].each do |thing| 

end 
@stuff[-1].do_something_else 
5
<% @stuff[0...-1].each do |thing| %> 
    <%= thing %> 
<% end %> 
<%= @stuff.last %> 
54
@stuff.each do |s| 
    ...normal stuff... 
    if s == @stuff.last 
    ...special stuff... 
    end 
end 
相關問題