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.
Pat M. (Guest)
on 2006-01-20 16: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
James G. (Guest)
on 2006-01-20 16:52
(Received via mailing list)
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
Pat M. (Guest)
on 2006-01-20 17:43
(Received via mailing list)
On 1/20/06, James Edward G. II <removed_email_address@domain.invalid> 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.
Daniel H. (Guest)
on 2006-01-20 17:52
(Received via mailing list)
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
This topic is locked and can not be replied to.