[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Question about variable scope

robin

1/27/2007 5:55:00 PM

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

2 Answers

Thomas Hafner

1/27/2007 6:24:00 PM

0

"robin" <robin.houston@gmail.com> wrote/schrieb <1169920481.252703.112350@a75g2000cwd.googlegroups.com>:

> 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

robin

1/28/2007 12:01:00 AM

0

On Jan 27, 6:24 pm, Thomas Hafner <tho...@hafner.NL.EU.ORG> 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