Simple scope question

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

On Wed, 7 Dec 2005, Glenn M. Lewis wrote:

load ‘file1.rb’
Any ideas?
i assume you are making a config file? why not use yaml?

-a

Glenn M. Lewis wrote:

load ‘file1.rb’

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

You can’t get quite the same scope. Check out Joel’s “Script” library
http://raa.ruby-lang.org/project/script/0.2 or use YAML or maybe even
something simple like this:

#!/usr/bin/env ruby

file1.rb

def file1() “\nCheers,\nDave” end

#!/usr/bin/env ruby

file2.rb

eval File.read(‘file1.rb’)
puts file1

C:/>file2.rb

Cheers,
Dave