From: Joel VanderWerf Date: 2005-12-19T07:46:24+09:00 Subject: Re: Newbie: require 'filename' - undefined local variable or method... Ezra Zygmuntowicz wrote: > > On Dec 18, 2005, at 2:27 PM, Grehom wrote: > >> Thanks Gene and Ezra, I tried your suggestions but with no luck. I >> modified the main program 'mainprog.rb' as follows: >> puts $: >> load("stuff.rb", wrap=false) >> puts myhash["a"] >> >> This produced following output: >> C:\rubysrcs>ruby mainprog.rb >> c:/ruby/lib/ruby/site_ruby/1.8 >> c:/ruby/lib/ruby/site_ruby/1.8/i386-msvcrt >> c:/ruby/lib/ruby/site_ruby >> c:/ruby/lib/ruby/1.8 >> c:/ruby/lib/ruby/1.8/i386-mswin32 >> . >> mainprog.rb:5: undefined local variable or method `myhash' for >> main:Object (NameError) >> >> and it seems the pwd '.' is part of the Load Path already (without me >> changing anything) >> >> So I'm still puzzled (there are a few examples of code like this in >> aforementioned tutorial book)! >> >> > > Yeah I was wrong in thinking that load would load local vars. So like > others have said you will have to wrap your var in a method or class. > Or you could eval the file by reading the file in and running eval on it. > > #a.rb > a = [1,2,3,4,5,6] > __________________ > > #b.rb > a_contents = File.open("a.rb"){|f| f.read} > eval a_contents > p a > > # => [1, 2, 3, 4, 5] > > -Ezra [~/tmp] cat >a.rb a = [1,2,3,4,5,6] [~/tmp] cat >b.rb a_contents = File.open("a.rb"){|f| f.read} eval a_contents p a [~/tmp] ruby b.rb b.rb:3: undefined local variable or method `a' for main:Object (NameError) [~/tmp] ruby -v ruby 1.8.2 (2004-12-25) [i686-linux] This only works if you assign to 'a' somewhere in b.rb before the eval. -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407