Kernel#load and locally scoped variables

J

John

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
 
J

Joel VanderWerf

John said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top