Question about variable scope

Does the following code behave as you’d expect?

2.times{|n| i,j = n,i; puts “i=#{i}, j=#{j.inspect}”}

Can you explain why j is nil rather than 0, the second time round?

Thanks,
Robin

“robin” [email protected] wrote/schrieb
[email protected]:

2.times{|n| i,j = n,i; puts “i=#{i}, j=#{j.inspect}”}

Can you explain why j is nil rather than 0, the second time round?

I’ll try. Everytime the block is executed, new variables n, i and j
are created, because they don’t already exist outside the block. If
you want i to be shared, it should already exist before, e.g.:

i = nil
2.times{|n| i,j = n,i; puts “i=#{i}, j=#{j.inspect}”}

Regards
Thomas

On 1/27/07, Thomas H. [email protected] wrote:

you want i to be shared, it should already exist before, e.g.:

i = nil
2.times{|n| i,j = n,i; puts “i=#{i}, j=#{j.inspect}”}

maybe OP thought that
i,j = n,i
is semantically equivalent to
i=n
j=i
but it is not :(, which is good :slight_smile:
the assignments are performed in parallel, and i is still nil when
assigned
to j.
But this is very useful thus one can e.g. swap
the value of two variables as follows

a,b = b,a

HTH
Robert

On Jan 27, 6:24 pm, Thomas H. [email protected] wrote:

I’ll try. Everytime the block is executed, new variables n, i and j
are created, because they don’t already exist outside the block. If
you want i to be shared, it should already exist before, e.g.:

i = nil
2.times{|n| i,j = n,i; puts “i=#{i}, j=#{j.inspect}”}

Thanks for the reply. I think I’ve succeeded in adjusting my mental
model enough that this now makes sense. :slight_smile:

Robin