I'm iterating through an array in ruby with each. Is there an easy way to get the iteration number or array index without going back to a for loop?
Luckily, there are several ways to get an index variable with foreach : Declare an integer variable before the loop, and then increase that one inside the loop with each loop cycle. Create a tuple that returns both the element's value and its index. Or swap the foreach loop with the for loop.
by using automatic destructuring: foreach (var (value, i) in Model.
Get The Current Array Index in JavaScript forEach()forEach(function callback(v) { console. log(v); }); The first parameter to the callback is the array value. The 2nd parameter is the array index.
Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.
Ah, got it.
each_with_index
woo!
edit: whoops!
For completeness' sake.
Thing.each_with_index {|obj, index_num| puts [obj, index_num].join(" has an index of ")}
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