How to do a for loop...and iterate a set number of times?

D

Dan No

So painfully basic, but I'm just starting Ruby and am coming to it from
C/C++/Java, etc. and some of the syntax is unnatural to me, and yes,
I've tried Google. I have an array of things and I want to access the
first 10...how do I do that?

for thing in things #(how do I set the beginning and end of the loop?)
#do something
end
 
I

Iñaki Baz Castillo

El Jueves, 29 de Enero de 2009, Dan No escribi=C3=B3:
for thing in things #(how do I set the beginning and end of the loop?)
#do something
end

things.each {|thing|
#do something
}

=2D-=20
I=C3=B1aki Baz Castillo
 
T

Tim Hunter

Dan said:
So painfully basic, but I'm just starting Ruby and am coming to it from
C/C++/Java, etc. and some of the syntax is unnatural to me, and yes,
I've tried Google. I have an array of things and I want to access the
first 10...how do I do that?

for thing in things #(how do I set the beginning and end of the loop?)
#do something
end

Usually collections define an each method. Each call into the block gets
the next element in the collection. You don't have to worry about the
beginning and end of the loop. The each method and its friends are
considered the most idiomatic.

ary.each {|element| ...}

Or if you just want the equivalent of a C for loop, use upto. The block
argument is the current count, starting with 'start':

start.upto(finish) {|n| ...}

Also there's step, which lets you use an increment other than 1:

start.step(finish, incr) {|n| ...}

It really depends on what you want to do.
 
J

Julian Leviston

It actually requires a little bit different thinking because once you
know idiomatic ruby, all the 'language' stuff you have to worry about
becomes stuff you just don't have to think about, like building new
arrays pit of existin ones, splitting things up, etc

Sent from my iPhone
 
R

Robert Dober

one solution would be:
for thing in things[0..9]
...
end
maybe
things.first( 10 ).each do |thing|
...
end
is a little bit more idiomatic.
Cheers
Robert
 
J

Julian Leviston

Um the beginning is the beginning and the end is the end. It's simple.
You don't have to manage it!

Sent from my iPhone
 
R

Robert Dober

Um the beginning is the beginning and the end is the end. It's simple. You
don't have to manage it!
We shall however consider the possibility that the properties of
Enumerable cannot be extended to metaphysics :)
R.
 

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,781
Messages
2,569,615
Members
45,297
Latest member
EngineerD

Latest Threads

Top