Rails 3.2确定每个块中的最后一个元素

时间:2013-01-07 00:26:31

标签: ruby-on-rails ruby-on-rails-3.2

鉴于以下代码,有没有办法测试迭代是否在最后一条记录上?我在我要测试的线路上给了一个小伪码。

@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

2 个答案:

答案 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