如何确定每个循环中的最后一个对象?

ala*_*dey 37 ruby-on-rails

在Rails中典型的每个循环中,如何确定最后一个对象,因为我想要做一些与其他对象不同的东西.

<% @stuff.each do |thing| %>

<% end %>
Run Code Online (Sandbox Code Playgroud)

abj*_*ror 61

@stuff.each do |s|
  ...normal stuff...
  if s == @stuff.last
    ...special stuff...
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 警告:如果@stuff元素不是唯一的,这将不起作用.即"a = [1,1]; a.map {| v | v == a.last}"返回[true,true].在整数的情况下,没有办法确定它是否真的是最后一个元素.如果使用其他对象,你可以使用相同的?(http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and) (13认同)
  • 这是最好的答案......如果你想要1-line它可能会更好.`s == @ stuff.last?"为最后的事情":"剩下的事情" (2认同)

A.A*_*Ali 29

有趣的问题.使用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
Run Code Online (Sandbox Code Playgroud)

  • @BenjaminBenoudis将是`if index == len - 1` (5认同)

jac*_*ipe 6

<% @stuff[0...-1].each do |thing| %>
  <%= thing %>
<% end %>
<%= @stuff.last %>
Run Code Online (Sandbox Code Playgroud)