[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How to know the index value on the each method

Elias Orozco

2/2/2009 5:14:00 PM

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
--
Posted via http://www.ruby-....

2 Answers

Stefano Crocco

2/2/2009 5:17:00 PM

0

Alle Monday 02 February 2009, Elias Orozco ha scritto:
> 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=C3=ADas

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

I hope this helps

Stefano


Elias Orozco

2/2/2009 5:42:00 PM

0

Thanks for the help. It was exactly what I needed. Thanks again,

Elías
--
Posted via http://www.ruby-....