Discussion in 'Ruby' started by robin, Jan 27, 2007.

1. robinGuest

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, Jan 27, 2007

2. Thomas HafnerGuest

"robin" <> wrote/schrieb <>:

> 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

Thomas Hafner, Jan 27, 2007

3. robinGuest

On Jan 27, 6:24 pm, Thomas Hafner <> 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.

Robin

robin, Jan 28, 2007