Iteration anomalu

Surely this is a FAQ but I can’t figure out how I would search for an
explanation for this behavior. In short, this code

a = [[1,2,3], [4,5,6], [7,8,9]]

for x in a do
print x, “\n”
end

for i in [0…a.length] do
print a[i], “\n”
end

yields this result:

123
456
789
123456789

Why does the second iteration evaluate all the prints before printing
the newline?

I have some puzzling variations on this too, but I am sure that the
answer to this will clear them up. Thanks!

FWIW, the reason I even consider the second iteration style, old-school
that it is, is because I want to do a double-nested iteration through a,
in this way:

for i in [0…a.length] do
for j in [i+1…a.length] do
# etc… processing lower-left-hand triangle of possibilities…

Yeah right, I meant anomaly…well that spelling was anomalous. :slight_smile:

Just try

for i in [0…a.length] do
print i
end

and you should have your answer.

Good Night…

Sascha A. wrote in post #1115792:

Just try

for i in [0…a.length] do
print i
end

and you should have your answer.

And to expand, in case it’s not entirely clear:

  • [x…y] constructs an Array with one element, and
    that element is a Range

  • Array#[] accepts a Range parameter

    for i in [0…a.length]
    i # i == (0…a.length)
    a[i] # same as: a[0…a.length]
    end

I believe you want to do this:

for i in 0…a.length do #<-- no brackets!
print a[i], “\n”
end

However, to be honest, this is one of the only times I’ve ever seen a
“for” loop written in Ruby code. The more typical, paradigmatic
approach would be:

a.each do |el|
print el, “\n”
end

… and for the nested iteration:

a.each_index do |i|
a[i+1…-1].each_with_index do |cell,j|
# processing on cell or j
end
end

… or something like that.
Also note that you can call .each on a range, e.g.:

(0…a.length).each do |i| …

Hi,

In second iteration the value we are getting in ‘i’ is [0…3]

Certainly it will print all the value of a and then it prints the new
line… it works properly.

try this…

for i in [0…a.length] do
print i
print a[i], “\n”
end

123456789

print a[0…2]

if you want the same result, try this it will print new line

for i in 0…a.length do
print a[i], “\n”
end

123
456
789

Cheers, Dhanabal