Ruby-on-rails 如何确定每个循环中的最后一个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/929178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:18:05 来源:igfitidea点击:
How to determine last object in each loop?
提问by alamodey
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.
在 Rails 中典型的每个循环中,我如何确定最后一个对象,因为我想对它做一些与其他对象不同的事情。
<% @stuff.each do |thing| %>
<% end %>
回答by abject_error
@stuff.each do |s|
...normal stuff...
if s == @stuff.last
...special stuff...
end
end
回答by A.Ali
Interesting question. Use an each_with_index.
有趣的问题。使用 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
回答by Hymanpipe
<% @stuff[0...-1].each do |thing| %>
<%= thing %>
<% end %>
<%= @stuff.last %>
回答by apostlion
A somewhat naive way to handle it, but:
一种有点幼稚的处理方式,但是:
<% @stuff.each_with_index do |thing, i| %>
<% if (i + 1) == @stuff.length %>
...
<% else %>
...
<% end %>
<% end %>
回答by Sam
A more lispy alternative is to be to use
一个更有趣的选择是使用
@stuff[1..-1].each do |thing|
end
@stuff[-1].do_something_else

