The
while
,
until
, and
for
loops are built into the
language and do not introduce new scope; previously existing locals
can be used in the loop, and any new locals created will be available
afterward.
The blocks used by iterators (such as
loop
and
each
) are
a little different. Normally, the local variables created in these
blocks are not accessible outside the block.
[ 1, 2, 3 ].each do |x|
y = x + 1
end
[ x, y ]
|
produces:
prog.rb:4: undefined local variable or method `x' for #<Object:0x401c2ce0> (NameError)
|
However, if at the time the block executes a local variable
already exists with the same name as that of a
variable in the block, the existing local variable will be used in the
block. Its value will therefore be available after the block finishes.
As the following example shows, this applies both to normal variables in the
block and to the block's parameters.
x = nil
|
y = nil
|
[ 1, 2, 3 ].each do |x|
|
y = x + 1
|
end
|
[ x, y ]
|
� |
[3, 4]
|