loop over array with indices

J

Johannes Ahlmann

hi,

i have the recurring problem that i want to loop over an array with
each/collect/... but (as an afterthought) need the index of the current
element.

for a while i have been using the "idiom":

array.zip((0..array.length).to_a).each {|a| ...}

but it really feels clunky, disfigures the source and feels like
something that would work really well in haskell, yet not in ruby ;-)
apart from looping with:

array.each_index {|i| a = array; ...}

are there any nice, rubyesque ways of doing this?

Johannes

BTW: what's the difference for an array of doing "array.each_index" as
opposed to "array.length.times"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top