Strange behaviour regarding lexical scopes?

Discussion in 'Ruby' started by Michal, Aug 27, 2004.

  1. Michal

    Michal Guest

    Hello,

    today (when explaining bits of Ruby to my friend)
    I got confused by this:

    $ cat a.rb
    b = 4
    if b == 1
    a = 1
    end
    p a

    $ ./a.rb
    nil

    $ ruby --version
    ruby 1.8.2 (2004-07-29) [i686-linux]

    (latest gentoo ebuild)

    Why is it that 'a' is nil and not undefined? (i would expect:

    undefined local variable or method `a' for main:Object (NameError)

    )

    Thanks in advance,
    M.
    --
    # Michal Safranek, email:
    a=(("a".."z").to_a+["@","."]);p(("%b"%[0x645bbb83a6a496]
    ).scan(/...../).map{|x|a[Integer("0b"+x)]}.join.reverse)
     
    Michal, Aug 27, 2004
    #1
    1. Advertising

  2. "Michal" <> schrieb im Newsbeitrag
    news:...
    > Hello,
    >
    > today (when explaining bits of Ruby to my friend)
    > I got confused by this:
    >
    > $ cat a.rb
    > b = 4
    > if b == 1
    > a = 1
    > end
    > p a
    >
    > $ ./a.rb
    > nil
    >
    > $ ruby --version
    > ruby 1.8.2 (2004-07-29) [i686-linux]
    >
    > (latest gentoo ebuild)
    >
    > Why is it that 'a' is nil and not undefined? (i would expect:
    >
    > undefined local variable or method `a' for main:Object (NameError)
    >
    > )
    >
    > Thanks in advance,
    > M.


    "if" doesn't introduce a new scope, similar to "switch" in C et. al. So "a"
    and "b" reside really in the same scope and the definition in the true
    clause is sufficient to make "a" defined. The assignment need not be
    executed.

    Kind regards

    robert
     
    Robert Klemme, Aug 27, 2004
    #2
    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. Michael Sparks

    Nested Scopes unintended behaviour ?

    Michael Sparks, Mar 17, 2010, in forum: Python
    Replies:
    4
    Views:
    280
    Terry Reedy
    Mar 18, 2010
  2. Fabian Streitel
    Replies:
    2
    Views:
    86
    Fabian Streitel
    Aug 16, 2009
  3. Joseph Ellis
    Replies:
    6
    Views:
    136
    Joseph Ellis
    Jul 25, 2003
  4. Michele Dondi
    Replies:
    5
    Views:
    89
    Michele Dondi
    Dec 3, 2004
  5. Paul Lalli

    convention regarding lexical filehandles

    Paul Lalli, Jan 13, 2005, in forum: Perl Misc
    Replies:
    14
    Views:
    179
    Michele Dondi
    Jan 16, 2005
Loading...

Share This Page