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?

Paul S. wrote:

.

Thank you.

.
On Mon, Sep 28, 2009 at 9:43 PM, Simon W. [email protected]
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 S.
http://www.nomadicfun.co.uk

[email protected]

On Mon, Sep 28, 2009 at 9:46 PM, Paul S. [email protected]
wrote:

.
On Mon, Sep 28, 2009 at 9:43 PM, Simon W. [email protected] 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

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

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

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs