Array#each - getting each element and the index

Is there a way to get each element of an array, as well the index of
that element? Something like
a = %w[foo bar]
a.each { |val, index| … } # val => ‘foo’, index => 0

If there’s no way to do that, is it better to use each_index and then
access the array?
a.each_index do |i|
puts i
puts a[i]
end

vs finding the index after you have the element
a.each do |val|
puts a.index(val)
puts val
end

Intuitively I’d think the second way may be a bit slower than the
first, because it has to search through the array for the element,
rather than accessing the index directly. Maybe not though…I’d just
like a bit of explanation on this.

Thanks,
Pat

On Jan 20, 2006, at 8:08 AM, Pat M. wrote:

Is there a way to get each element of an array, as well the index of
that element?

You bet.

Something like
a = %w[foo bar]
a.each { |val, index| … } # val => ‘foo’, index => 0

a.each_with_index …

James Edward G. II

On 1/20/06, James Edward G. II [email protected] wrote:

a.each_with_index …

James Edward G. II

Perfect, thanks

Is this using some idiom (e.g. attaching _with_index) that I don’t
know about? I didn’t see that method in the Array rdoc.

On Jan 20, 2006, at 4:06 PM, Pat M. wrote:

Is this using some idiom (e.g. attaching _with_index) that I don’t
know about? I didn’t see that method in the Array rdoc.

If you do a ``ri Array’’ you will see that #each_with_index is mixed
in from Enumerable. see Enumerable#each_with_index for more information.

– Daniel