Noob - loop indexing

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?

···

--
Posted via http://www.ruby-forum.com/.

.

···

On Mon, Sep 28, 2009 at 9:43 PM, Simon Willard <simonwillard@gmail.com> 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

--
Paul Smith
http://www.nomadicfun.co.uk

paul@pollyandpaul.co.uk

Paul Smith wrote:

.

Thank you.

···

--
Posted via http://www.ruby-forum.com/\.

Or

a.each_with_index do |x, i|
  #here, x is a[i]
  puts x,i
end

···

On Mon, Sep 28, 2009 at 9:46 PM, Paul Smith <paul@pollyandpaul.co.uk> wrote:

.
On Mon, Sep 28, 2009 at 9:43 PM, Simon Willard <simonwillard@gmail.com> 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

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?"

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 :wink:

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com

···

On Sep 28, 2009, at 4:49 PM, Paul Smith wrote:

On Mon, Sep 28, 2009 at 9:46 PM, Paul Smith > <paul@pollyandpaul.co.uk> wrote:

On Mon, Sep 28, 2009 at 9:43 PM, Simon Willard <simonwillard@gmail.com >> > wrote:

On Sep 28, 2009, at 4:43 PM, Simon Willard wrote: