Question about variable scope

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

  1. robin

    robin Guest

    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
    #1
    1. Advertising

  2. "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
    #2
    1. Advertising

  3. robin

    robin Guest

    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
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    940
    Paul Opal
    Oct 11, 2004
  2. ann
    Replies:
    13
    Views:
    661
    Patricia Shanahan
    Sep 13, 2005
  3. Steven T. Hatton
    Replies:
    9
    Views:
    472
  4. David Filmer
    Replies:
    19
    Views:
    237
    Kevin Collins
    May 21, 2004
  5. Andrew Falanga
    Replies:
    2
    Views:
    198
    Andrew Falanga
    Nov 22, 2008
Loading...

Share This Page