鉴于以下代码,有没有办法测试迭代是否在最后一条记录上?我在我要测试的线路上给了一个小伪码。
@shipments.each do |shipment|
puts shipment.id
puts shipment.desc
unless shipment.last? #is there a way to do this line?
puts "that was the last shipment"
end
end
答案 0 :(得分:1)
没有内置方法,但最接近这个的方法可能是:
unless shipment == @shipments.last
这假设您正在使用一组ActiveRecord结果,因为如果@shipments
是[1, 2, 3, 2]
之类的数组,2
将匹配第二个元素以及最后一个元素。
答案 1 :(得分:1)
使用#last方法你可以做类似的事情,但我相信应该有更好的方法来实现这个目标
@shipments.each do |shipment|
puts shipment.id
puts shipment.desc
unless shipment == @shipments.last #is there a way to do this line?
puts "that was the last shipment"
end
end