0

给定以下代码,有没有办法测试迭代是否在最后一条记录上?我在我想测试的行上给出了一些伪代码。

@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
4

2 回答 2

1

没有内置方法,但最接近此方法的可能是:

unless shipment == @shipments.last

这假设您正在处理一组 ActiveRecord 结果,因为如果@shipments是一个数组,例如[1, 2, 3, 2],2将匹配第二个元素以及最后一个元素。

于 2013-01-07T00:39:03.267 回答
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
于 2013-01-07T00:39:29.707 回答