I want to do something different with the last loop iteration when performing 'foreach' on an object. I'm using Ruby but the same goes for C#, Java etc.
list = ['A','B','C']
list.each{|i|
puts "Looping: "+i # if not last loop iteration
puts "Last one: "+i # if last loop iteration
}
The output desired is equivalent to:
Looping: 'A'
Looping: 'B'
Last one: 'C'
The obvious workaround is to migrate the code to a for loop using 'for i in 1..list.length'
, but the for each solution feels more graceful. What is the most graceful way to code a special case during a loop? Can it be done with foreach?
Best Solution
I see a lot of complex, hardly readable code here... why not keep it simple:
It's only one extra statement!
Another common situation is that you want to do something extra or less with the last item, like putting a separator between the items: