How to determine array element number in a each loop

Hello all, newbie here.

The title is quite self explanatory: I am in

dummy_array.each do |a|
#code here
end

and I want to know which element (the number n in nth element) of the
dummy_array.

Thanks in advance :slight_smile:

ยทยทยท

--
Posted via http://www.ruby-forum.com/.

The title is quite self explanatory: I am in

dummy_array.each do |a|
#code here
end

and I want to know which element (the number n in nth element) of the
dummy_array.

You could just put a counting variable in there:

i = 0

dummy_array.each do |a|

i = i+1

#code here
end

You can also use each_index on the array if you'd like.

http://ruby-doc.org/core/classes/Array.html#M002174

dummy_array.each_index do |i|
ย ย ย ย a = array[i]
end

ยทยทยท

On Jul 28, 6:24 pm, Kaya Aykut <kaya.ay...@gmail.com> wrote:

or use each_with_index
http://ruby-doc.org/core/classes/Enumerable.html#M003137

ยทยทยท

On Thu, Jul 29, 2010 at 8:41 AM, James Harrison <oscartheduck@gmail.com>wrote:

>
> The title is quite self explanatory: I am in
>
> dummy_array.each do |a|
> #code here
> end
>
> and I want to know which element (the number n in nth element) of the
> dummy_array.
>

You could just put a counting variable in there:

i = 0
> dummy_array.each do |a|
i = i+1
> #code here
> end

You can also use each_index on the array if you'd like.

class Array - RDoc Documentation