Array#each - getting each element and the index

P

Pat Maddox

Is there a way to get each element of an array, as well the index of
that element? Something like
a =3D %w[foo bar]
a.each { |val, index| .... } # val =3D> 'foo', index =3D> 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
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
 
J

James Edward Gray II

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 Gray II
 
R

Robert Klemme

Pat said:
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

a.each_with_index { |val, index| .... }

robert
 
C

ChrisH

Pat said:
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

Yes, and suprisingly it called each_with_index 9^)

Cheers
 
P

Pat Maddox

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

You bet.
Something like
a =3D %w[foo bar]
a.each { |val, index| .... } # val =3D> 'foo', index =3D> 0

a.each_with_index ...

James Edward Gray 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.
 
D

Daniel Harple

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
 
M

Marcin Mielżyński

Pat said:
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.

It is a plain method name.

Enumerable#each_with_index

lopex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,834
Latest member
BuyCannaLabsCBD

Latest Threads

Top