ahnbizcad
ahnbizcad

Reputation: 10807

Obtain increment value in a non-numeric array loop/

It's easy to obtain the current loop iteration's count when looping over a sequential numeric array.

(1..5)each do |num|
  @output[num] = num
end

But what if I need to loop on a collection of objects (that aren't sequential numeric collections), how do I obtain the increment value of the loop?

@objects.each do |obj|
  @output[obj] = obj.name
end

Obviously, the index is invalid. What is the ruby way to do what is clearly intended here (obtain an explicit numeric integer corresponding to the count of the loop cycle?

Upvotes: 0

Views: 202

Answers (1)

Andrew
Andrew

Reputation: 1851

Use the each_with_index method. It iterates over the elements of the collection giving you both the item and the index. It works on unordered enumerations too, although the order might be inconsistent.

Upvotes: 1

Related Questions