Grehom wrote:
I have one line of code in a file called 'stuff.rb':
myhash = { "a" => "ay", "b" => "bee", "c" => "sea" }
and I wish to include it in another program called 'mainprog.rb' thus:
require 'stuff'
puts " a = " + myhash["a"]
when I run it I get an error message:
mainprog.rb:4: undefined local variable or method `myhash' for
main:Object (NameError)
Local vars are scoped to the file they are defined in, when you use
require or load. You could make it global, but unless this is just a
quick hack, it's not a good solution.
Another option is to read and eval the file. If the myhash variable has
been assigned *before* you eval, then the assignment in stuff.rb will
propagate to the mainprog.rb. Like so:
myhash = nil
eval File.read("stuff.rb")
p myhash
This is ok for some purposes, but you have to know in advance which
variables the file is going to define. Also, you may have scope
collisions: any other local var in mainprog.rb can be affected by
assignments in stuff.rb.
My preference is to read the file as a string and use module_eval:
# mainprog.rb
m = Module.new
m.module_eval(File.read("stuff.rb"), File.expand_path("stuff.rb"))
p m::Myhash
# stuff.rb
Myhash = { "a" => "ay", "b" => "bee", "c" => "sea" }
Local vars stay local. Constants are accessible in the scope of the
newly defined module m. The second arg to module_eval means that errors
are reported with the correct file name.
<plug> This is the approach used by my "script" lib on raa. It adds some
sugar and features. </plug>
···
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407