From: "Brian Schröder" Date: 2005-08-19T04:08:48+09:00 Subject: Re: require question On 18/08/05, Gaston Garcia wrote: > Hello to the ruby-talkers. It's my first week with ruby, I'm reading Why's > poingnant guide currently. I'm not a programmer, my only knowledge is a > little php I use to do web stuff and some actionScript cus I do some Flash. > I thought of learning to program and Ruby is what I've chosen (even though > Eric Raymond says to learn Python is what he thinks is best). Anyways I > don't care, Why's poignant guide is funny as hell, and that's it. I wanna be > a part of it. > > Now my question is (I'm assuming) a very simple one: > > I'm trying to use the 'require' Kernel method. > > I save a file as 'my_string.rb' and it contains just this: > > my_string = 'hello world' > > On another ruby file saved as 'my_string_reader.rb' I write: > > require 'my_string' > > puts 'my_string' > > I thought that would output my 'hello world', but I get "undefined local > variable or method 'my_string' for main:Object (NameError) > > I'm using windows xp. But the same problem happened on Ubuntu Linux. Same > error. It's the only example from Why's poignant guide that gives me errors. > It's as if it's not reading the variables I've got stored in the required > file. > > Thanks for your help. > > > -- > -gaston > > Unlike with php ruby does not simple include the sourcefile at the point of the require, but it takes extra care not to clobber any local variables. Require calls load and in the description of load this is mentioned: # ri Kernel#load ------------------------------------------------------------ Kernel#load load(filename, wrap=false) => true ------------------------------------------------------------------------ Loads and executes the Ruby program in the file _filename_. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in +$:+. If the optional _wrap_ parameter is +true+, the loaded script will be executed under an anonymous module, protecting the calling program's global -> namespace. In no circumstance will any local variables in the <- -> loaded file be propagated to the loading environment. <- If you want to include a constant value from a file that is possible: --- r.rb --- require 'r1' puts A --- --- --- r2.rb --- A = 12 --- --- ruby r.rb => 12 regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/