Hi,
I’d like to ask for some help with local variable scope. I understand
that the scope of a local variable is the “do…end” block in which it
is created. However, the code below shows that the value assigned to
the variable within a block does not persist after the single
iteration in which the variable is given that value, although the
variable is still defined in a later iteration. That is, in the idx=2
iteration, Ruby does not remember that a=11 in the previous iteration,
but it also does not complain about an undefined local variable “a”
(which it of course does outside the block). I haven’t been able to
find this behavior mentioned in the documentation or in this
group–can you point me to something that will clarify for me what is
going on?
Thanks,
Steve
data=[1,2]
data.each do | idx|
if idx == 1
a = 11
print “idx=1: a=”,a,“\n”
elsif idx == 2
b = 12
print “idx=2: a=”,a," b=“,b,”\n"
end
end
print “after:\n”
print “a=”,a," b=“,b,”\n"
c:\ruby\bin\ruby test.rb
idx=1: a=11
idx=2: a=nil b=12
after:
test.rb:12: undefined local variable or method `a’ for main:Object
(NameError)
···
Exit code: 1