Forum: Ruby Question about variable scope

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B7d4b678a3b4ff1b80f5c6e70d87d04e?d=identicon&s=25 robin (Guest)
on 2007-01-27 18:56
(Received via mailing list)
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
8029153bbcbda4a6844440c93e0c6422?d=identicon&s=25 Thomas Hafner (Guest)
on 2007-01-27 19:36
(Received via mailing list)
"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
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-01-27 20:27
(Received via mailing list)
On 1/27/07, Thomas Hafner <thomas@hafner.nl.eu.org> 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 :)
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
B7d4b678a3b4ff1b80f5c6e70d87d04e?d=identicon&s=25 robin (Guest)
on 2007-01-28 01:05
(Received via mailing list)
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
This topic is locked and can not be replied to.