For statements

Hi,

Is there a way to do a for statement of this form?:

for (i = 0; i < num; i += 3) …

Does the for statement have any form other than ‘for i in array …’?

Can I use a for statement to do the equivalent this?:
3.step(9,2) {|i| puts i }

Thanks for the help.
Daniel.

The step method is the Ruby-idiomatic way to do a for loop. Also times and
upto.

···

On Mon, 02 Dec 2002 09:28:39 +0900, Daniel Carrera wrote:

Hi,

Is there a way to do a for statement of this form?:

for (i = 0; i < num; i += 3) …

Does the for statement have any form other than ‘for i in array …’?

Can I use a for statement to do the equivalent this?:
3.step(9,2) {|i| puts i }

Thanks for the help.
Daniel.

Question is, why do you want to? You’ve found a clear way to accomplish it
using step. Perhaps you want to modify the loop boundary while the loop is
executing…

So, if you really want to emulate the C-style for loop, simply use a while
loop. The C-style for loop is really just a while loop in disguise.

i = 3
num = 9
while i <= num do
puts i
i += 2
end

-michael

···

On Sunday 01 December 2002 18:28, Daniel Carrera wrote:

for (i = 0; i < num; i += 3) …

Does the for statement have any form other than ‘for i in array …’?

Can I use a for statement to do the equivalent this?:
3.step(9,2) {|i| puts i }

You know that Ranges can be handy with the for…in?

for i in (3…9).reject { |i| i % 2 == 0 }
puts i
end

for i in (3…9)
next if i % 2 == 0
puts i
end

_why

···

Daniel Carrera (dcarrera@math.umd.edu) wrote:

Can I use a for statement to do the equivalent this?:
3.step(9,2) {|i| puts i }

Question is, why do you want to? You’ve found a clear way to accomplish it
using step. Perhaps you want to modify the loop boundary while the loop is
executing…

I don’t need to. I’m just trying to learn Ruby.

Thanks.

Why gives some good suggestions, but why do you
want to use a for stateement?
For the case given, I think #step is more applicable and probably faster:

3.step(9,2) { |i|
puts i
}

···

On Monday, 2 December 2002 at 11:28:58 +0900, why the lucky stiff wrote:

Daniel Carrera (dcarrera@math.umd.edu) wrote:

Can I use a for statement to do the equivalent this?:
3.step(9,2) {|i| puts i }

You know that Ranges can be handy with the for…in?

for i in (3…9).reject { |i| i % 2 == 0 }
puts i
end

for i in (3…9)
next if i % 2 == 0
puts i
end


Jim Freeze

Nothing astonishes men so much as common sense and plain dealing.

Why gives some good suggestions, but why do you
want to use a for stateement?

I don’t need a for statement. I just want to learn how Ruby works.

Daniel.