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…
[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.: