From: Rob Biedenharn Date: 2009-09-29T06:07:12+09:00 Subject: Re: Noob - loop indexing On Sep 28, 2009, at 4:49 PM, Paul Smith wrote: > On Mon, Sep 28, 2009 at 9:46 PM, Paul Smith > wrote: >> On Mon, Sep 28, 2009 at 9:43 PM, Simon Willard > > wrote: >>> I try to make Ruby loops using "each" like this: >>> >>> # a is an array >>> a.each do ... end >> >> a.each_index do |i| >> a[i]... >> end > > Or > > a.each_with_index do |x, i| > #here, x is a[i] > puts x,i > end But just as importantly, ask yourself the question: "Why do I need the index? Am I not letting the objects do their thing?" On Sep 28, 2009, at 4:43 PM, Simon Willard wrote: > 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? 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@AgileConsultingLLC.com