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?
Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.
The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.
This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
I see a lot of complex, hardly readable code here... why not keep it simple:
var count = list.Length; foreach(var item in list) if (--count > 0) Console.WriteLine("Looping: " + item); else Console.Writeline("Lastone: " + item);
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:
var count = list.Length; foreach(var item in list) { Console.Write(item); if (--count > 0) Console.Write(","); }
The foreach construct (in Java definitely, probably also in other languages) is intended to represent the most general kind if iteration, which includes iteration over collections that have no meaningful iteration order. For example, a hash-based set does not have an ordering, and therefore there is no "last element". The last iteration may yield a different element each time you iterate.
Basically: no, the foreach construct is not meant to be used that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With