From: Joel VanderWerf Date: 2005-12-07T03:56:00+09:00 Subject: Re: simple scope question Glenn M. Lewis wrote: > Is it possible to place another file within the same scope > as another file that loads it? > For example, I can't get this to work: > ----------------------------------------- > #!/usr/bin/env ruby > # file1.rb > file1 = "something" > ----------------------------------------- > #!/usr/bin/env ruby > # file2.rb > load 'file1.rb' > puts file1 > ----------------------------------------- > > C:/>file2.rb > C:/file2.rb:4: undefined local variable or method `file1' for > main:Object (NameError) > > Of course, I could make them global variables, but it would be nice if I > could load it > in with the same scope. > > Any ideas? > Thanks! > -- Glenn Lewis The best solution I've found is to read file1.rb and module_eval it's contents in the scope of a new module. Then, if you've defined constants and methods in file1.rb, you can access them through the module. You can't get the local vars this way (which may be a good thing). (See the script project on RAA for an elaboration of this approach.) It's also possible to assign to the local vars before loading file1.rb, read file1.rb, eval it, and then the local variables will be updated. But you have to know in advance what local variables file1.rb has: ruby -e "x=1; eval 'x=2;y=3'; p x, y" -e:1: undefined local variable or method `y' for main:Object (NameError) ruby -e "x=1; eval 'x=2;y=3'; p x" 2 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407