Reputation: 2195
Given the following code, is there a way to test whether the iteration is on the last record? I have given a little pseudocode on the line I would like to test.
@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
Upvotes: 0
Views: 306
Reputation: 6356
By using the #last method you could do something like that, but I believe there should be a better way to achieve this
@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
Upvotes: 1
Reputation: 124419
There is no built-in method, but the closest to this would probably be something like:
unless shipment == @shipments.last
This assumes you're working with a set of ActiveRecord results, because if @shipments
was an array such as [1, 2, 3, 2]
, 2
would match the second element as well as the last.
Upvotes: 1