Block binding does not contains local variable

Discussion in 'Ruby' started by Artem Voroztsov, Apr 18, 2008.

  1. Maybe it contains.
    But please, explain me why "block binding" does not print a, b, and c
    variables.

    def vars(&block)
    b = block.call(55)
    puts "inner binding: ", eval("local_variables", b)
    puts "block binding: ", eval("local_variables", block.binding)
    end

    vars {|a|
    b = 1
    c = 2
    binding
    }

    My output:

    ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
    inner binding:
    c
    b
    a
    block binding:
     
    Artem Voroztsov, Apr 18, 2008
    #1
    1. Advertising

  2. Hi --

    On Fri, 18 Apr 2008, Artem Voroztsov wrote:

    > Maybe it contains.
    > But please, explain me why "block binding" does not print a, b, and c
    > variables.
    >
    > def vars(&block)
    > b = block.call(55)
    > puts "inner binding: ", eval("local_variables", b)
    > puts "block binding: ", eval("local_variables", block.binding)
    > end
    >
    > vars {|a|
    > b = 1
    > c = 2
    > binding
    > }
    >
    > My output:
    >
    > ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
    > inner binding:
    > c
    > b
    > a
    > block binding:


    My understanding is that given a Proc, there's no way that Ruby can
    know what local variables are created inside it without running it, so
    binding of the Proc itself is the binding of the local context where
    it's created. It's only when the block is run that the local variables
    inside the block get bound to anything, so binding inside the block is
    a different binding and includes those variables.

    You can see this if you do:

    x = 1

    and then call vars. block.binding will then include x.


    David

    --
    Rails training from David A. Black and Ruby Power and Light:
    INTRO TO RAILS June 9-12 Berlin
    ADVANCING WITH RAILS June 16-19 Berlin
    INTRO TO RAILS June 24-27 London (Skills Matter)
    See http://www.rubypal.com for details and updates!
     
    David A. Black, Apr 18, 2008
    #2
    1. Advertising

  3. Thank you!
     
    Artem Voroztsov, Apr 20, 2008
    #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. James Dyer
    Replies:
    5
    Views:
    648
  2. Daniel
    Replies:
    5
    Views:
    551
    Chris Uppal
    Jul 22, 2004
  3. morrell
    Replies:
    1
    Views:
    963
    roy axenov
    Oct 10, 2006
  4. Amir Ebrahimifard

    Block variable & Local variable

    Amir Ebrahimifard, Aug 3, 2010, in forum: Ruby
    Replies:
    7
    Views:
    124
    Barchil Barchil
    Aug 10, 2010
  5. David Filmer
    Replies:
    19
    Views:
    246
    Kevin Collins
    May 21, 2004
Loading...

Share This Page