Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Kernel#load and locally scoped variables

Reply
Thread Tools

Kernel#load and locally scoped variables

 
 
John
Guest
Posts: n/a
 
      07-09-2004
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
 
Reply With Quote
 
 
 
 
Joel VanderWerf
Guest
Posts: n/a
 
      07-09-2004
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.


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
foreach loops and lexically scoped loop variables Derek Basch Perl Misc 6 05-29-2006 07:44 AM
Initial values of File scoped and Block level variables Madhav C Programming 27 01-16-2006 03:29 AM
Initial values of File scoped and Block level variables Madhav C Programming 4 01-08-2006 01:44 PM
Viewing variables within process scoped procedures (Modelsim) Mark VHDL 4 11-09-2004 11:13 PM
block scoped variables Andy Fish Java 3 08-16-2003 02:51 PM



Advertisments