给定以下代码,有没有办法测试迭代是否在最后一条记录上?我在我想测试的行上给出了一些伪代码。
@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
给定以下代码,有没有办法测试迭代是否在最后一条记录上?我在我想测试的行上给出了一些伪代码。
@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
没有内置方法,但最接近此方法的可能是:
unless shipment == @shipments.last
这假设您正在处理一组 ActiveRecord 结果,因为如果@shipments
是一个数组,例如[1, 2, 3, 2]
,2
将匹配第二个元素以及最后一个元素。
通过使用#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