Kernel#load and locally scoped variables

Discussion in 'Ruby' started by John, Jul 9, 2004.

  1. John

    John Guest

    Is there any way for a Kernel#load(file) code block to gain access to
    the variables that are in scope at the point at which that file is
    loaded? Anyone have a code example that they could share? Or an
    explanation as to why it doesn't work?

    Thanks

    John
    John, Jul 9, 2004
    #1
    1. Advertising

  2. John wrote:
    > Is there any way for a Kernel#load(file) code block to gain access to
    > the variables that are in scope at the point at which that file is
    > loaded? Anyone have a code example that they could share? Or an
    > explanation as to why it doesn't work?


    Sure. Use read and eval instead of load:

    ---- a.rb ----

    x = nil # the variable must "exist" before the eval
    load "b.rb"
    p x # ==> nil
    eval File.read("b.rb")
    p x # ==> 1

    ---- b.rb ----

    x = 1

    ----

    This is a little "evil", though. My preferred alternative is to wrap the
    loaded file in a module and use that module's scope to access methods
    and constants (but local vars stay local), as in
    http://ruby-talk.org/100429.
    Joel VanderWerf, Jul 9, 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. Madhav
    Replies:
    4
    Views:
    302
    Kenny McCormack
    Jan 8, 2006
  2. Madhav
    Replies:
    27
    Views:
    560
    Dave Thompson
    Jan 16, 2006
  3. yogesh
    Replies:
    3
    Views:
    585
    Kenny McCormack
    Feb 12, 2006
  4. Replies:
    3
    Views:
    166
  5. Lars Gierth
    Replies:
    6
    Views:
    217
    David Masover
    Mar 20, 2010
Loading...

Share This Page