Forum: Ruby Array#each - getting each element and the index

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2006-01-20 15:46
(Received via mailing list)
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
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-01-20 15:52
(Received via mailing list)
On Jan 20, 2006, at 8:08 AM, Pat Maddox 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 Gray II
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2006-01-20 16:43
(Received via mailing list)
On 1/20/06, James Edward Gray II <james@grayproductions.net> wrote:
>
> 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.
9358cc96c46055cd68d4a76a9aefe026?d=identicon&s=25 Daniel Harple (Guest)
on 2006-01-20 16:52
(Received via mailing list)
On Jan 20, 2006, at 4:06 PM, Pat Maddox 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
This topic is locked and can not be replied to.