Newbie question - ruby equivalence of for loop?

is there an equivalence in Ruby for the nested “for loop” in java.
i want to complete the following:
i is 0
j is 2
j is 4
j is 6
j is 8
i is 1
j is 2
j is 4
j is 6
j is 8
i is 2
j is 2
j is 4
j is 6
j is 8
but want to use Ruby,(i think Rails has a foreach loop).I can do the
above in Java
but Ruby is still foreign to me.Whats the best method to implement the
above?


Posted with NewsLeecher v3.9 Beta 1
Web @ NewsLeecher - The Complete Usenet Package


On Apr 6, 2007, at 6:25 PM, [email protected] wrote:

is there an equivalence in Ruby for the nested “for loop” in java.
i want to complete the following:
i is 0
j is 2
j is 4
j is 6
j is 8

If you are just trying to iterate over the numeric ranges:

(0…2).each { |i|
2.step(8, 2) { |j|
puts “#{i}, #{j}”
}
}

Gary W.

thanks for the code Gary, I’m goin work through it.its quite different
from how I implemented the
solution in java,(it really is a paradigm shift), thanks again for the
reply


Posted with NewsLeecher v3.9 Beta 1
Web @ NewsLeecher - The Complete Usenet Package


On 4/6/07, [email protected] [email protected] wrote:

How did you do it in Java, might I ask, that might help us help you
understand the ruby way.

On Apr 6, 2007, at 7:15 PM, [email protected] wrote:

thanks for the code Gary, I’m goin work through it.its quite
different from how I implemented the
solution in java,(it really is a paradigm shift), thanks again for
the reply

This alternative version is a bit simpler.
It might be better to understand this one and
then go back to my first one:

[0,1,2].each { |i|
[2,4,6,8].each { |j|
puts “#{i}, #{j}”
}
}

Gary W.

On 07.04.2007 00:21, [email protected] wrote:

    j is 6
    j is 8
i is 2
    j is 2
    j is 4
    j is 6
    j is 8

but want to use Ruby,(i think Rails has a foreach loop).I can do the above in Java
but Ruby is still foreign to me.Whats the best method to implement the above?

irb(main):005:0> 0.upto 2 do |i|
irb(main):006:1* 2.step 8, 2 do |j|
irb(main):007:2* print i, " ", j, “\n”
irb(main):008:2> end
irb(main):009:1> end
0 2
0 4
0 6
0 8
1 2
1 4
1 6
1 8
2 2
2 4
2 6
2 8
=> 0

You can also use a for loop for the outer loop:

irb(main):010:0> for i in 0…2 do
irb(main):011:1* puts i
irb(main):012:1> end
0
1
2
=> 0…2

The scoping is a bit different, i.e. i is known after the loop.

Kind regards

robert