Noob - loop indexing

Discussion in 'Ruby' started by Simon Willard, Sep 28, 2009.

  1. I try to make Ruby loops using "each" like this:

    # a is an array
    a.each do ... end

    But I always end up needing the array index in the body of the loop for
    one reason or another. Then I change it to:

    i=0;
    while i<a.length do
    ...
    i+=1
    end

    But this feels clunky and less Ruby-like. Is there a way to access the
    index in an "each" loop? Is there a more elegant way to create an
    indexed loop?
     
    Simon Willard, Sep 28, 2009
    #1
    1. Advertisements

  2. Thank you.
     
    Simon Willard, Sep 28, 2009
    #2
    1. Advertisements

  3. Simon Willard

    Paul Smith Guest

     
    Paul Smith, Sep 28, 2009
    #3


  4. But just as importantly, ask yourself the question:
    "Why do I need the index? Am I not letting the objects do their
    thing?"


    If your question were a bit different, then the answer might be:

    a.length.times do |i|
    #...
    end

    or even

    (0...a.length).each do |i|
    #...
    end
    # and note the use of the ... range constructor that excludes its end.

    (and, of course, it's up to you to formulate the appropriate
    question ;-)

    -Rob

    Rob Biedenharn http://agileconsultingllc.com
     
    Rob Biedenharn, Sep 28, 2009
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.