Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the array index or iteration number with an each iterator?

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?

like image 232
Jonathan Adelson Avatar asked Apr 01 '09 15:04

Jonathan Adelson


People also ask

How do you find the index value of A for each 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.

How do you get the index of the current iteration of a forEach loop?

by using automatic destructuring: foreach (var (value, i) in Model.

Can we get index in forEach JavaScript?

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.

Is there a way to access an iteration counter in Java for each loop?

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.


2 Answers

Ah, got it.

each_with_index

woo!

edit: whoops!

like image 130
Jonathan Adelson Avatar answered Sep 30 '22 21:09

Jonathan Adelson


For completeness' sake.

Thing.each_with_index {|obj, index_num| puts [obj, index_num].join(" has an index of ")}
like image 28
pjammer Avatar answered Sep 30 '22 21:09

pjammer