Forum: Ruby How to know the index value on the each method

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.
Elias O. (Guest)
on 2009-02-02 19:13
Hello,

I was wondering if there is a way to access the current index value when
using the each method to iterate over an array. For example,

@pancakes.each do |pancake|

  puts pancake
  # How can I ask which is the current index value of pancake. I wish to
know in what position is the pancake object on the array without using a
local integer variable to count up.

end

Thanks,

Elías
Stefano C. (Guest)
on 2009-02-02 19:18
(Received via mailing list)
Alle Monday 02 February 2009, Elias O. ha scritto:
> local integer variable to count up.
>
> end
>
> Thanks,
>
> Elías

You can use Array#each_with_index, instead of Array#each. Or you can use
Array#index to obtain the index of the current object, but it only works
if
the array doesn't contain duplicates: if there are duplicates (according
to
==), Array#index always returns the index of the first item.

I hope this helps

Stefano
Flower B. (Guest)
on 2009-02-02 19:21
(Received via mailing list)
* Elias O. <removed_email_address@domain.invalid> [2009-02-03 02:13:32 +0900]:

> Hello,
>
> I was wondering if there is a way to access the current index value when
> using the each method to iterate over an array. For example,
>
> @pancakes.each do |pancake|

@pancakes.each_with_index do |pancake, i|

Jan
Elias O. (Guest)
on 2009-02-02 19:42
Thanks for the help. It was exactly what I needed. Thanks again,

Elías
This topic is locked and can not be replied to.