loop over array with indices

Discussion in 'Ruby' started by Johannes Ahlmann, May 23, 2005.

  1. 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"?
     
    Johannes Ahlmann, May 23, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. SnuSnu
    Replies:
    6
    Views:
    341
    Steven Rumbalski
    Apr 25, 2004
  2. KLaus Blank
    Replies:
    1
    Views:
    455
  3. mt

    Multiple indices in for loop

    mt, Mar 29, 2011, in forum: C Programming
    Replies:
    3
    Views:
    347
    J. J. Farrell
    Mar 30, 2011
  4. Billy Mays

    Better way to iterate over indices?

    Billy Mays, Jun 21, 2011, in forum: Python
    Replies:
    4
    Views:
    194
    Ethan Furman
    Jun 21, 2011
  5. Isaac Won
    Replies:
    9
    Views:
    397
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page