Forum: Ruby simple scope question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
1d8d318b49aebd4265b6da27efe6f8c6?d=identicon&s=25 noSpam (Guest)
on 2005-12-06 19:07
(Received via mailing list)
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
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 ara.t.howard (Guest)
on 2005-12-06 19:35
(Received via mailing list)
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
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 vjoel (Guest)
on 2005-12-06 20:00
(Received via mailing list)
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
1279eedc4a964ac0e75ce8ce33e84178?d=identicon&s=25 dave.burt (Guest)
on 2005-12-07 00:01
(Received via mailing list)
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
This topic is locked and can not be replied to.