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. Advertisements

  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. Advertisements

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. Mark
    Replies:
    4
    Views:
    9,892
    mike_treseler
    Nov 9, 2004
  2. Andy Fish

    block scoped variables

    Andy Fish, Aug 15, 2003, in forum: Java
    Replies:
    3
    Views:
    609
    Chris Uppal
    Aug 16, 2003
  3. Madhav
    Replies:
    4
    Views:
    423
    Kenny McCormack
    Jan 8, 2006
  4. Madhav
    Replies:
    27
    Views:
    749
    Dave Thompson
    Jan 16, 2006
  5. yogesh
    Replies:
    3
    Views:
    787
    Kenny McCormack
    Feb 12, 2006
  6. Replies:
    3
    Views:
    360
  7. Lars Gierth
    Replies:
    6
    Views:
    481
    David Masover
    Mar 20, 2010
  8. Derek Basch
    Replies:
    6
    Views:
    338
    Michele Dondi
    May 29, 2006
Loading...