Noob - loop indexing

S

Simon Willard

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

Rob Biedenharn

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...
end


Or

a.each_with_index do |x, i|
#here, x is a
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 ;-)

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top