From: Randy Kramer Date: 2007-11-09T06:39:04+09:00 Subject: Re: local variables, eval, and parsing On Thursday 08 November 2007 01:45 pm, furtive.clown@gmail.com wrote: > On Nov 8, 1:10 pm, Randy Kramer wrote: > > On Thursday 08 November 2007 11:25 am, furtive.cl...@gmail.com wrote: > > > > > As explained in the links I gave, the problem is due to the > > > determination of local variables at compile time. Really all that is > > > needed is a way to insert code before parsing, like perl's BEGIN block. > > > > Ruby has a BEGIN {} (and END) block as well--have you tried that? (pickaxe2 > > pg. 318) > > > > BEGIN { > eval "foo = 99" > } > puts foo > > => test.rb:6: undefined local variable or method `foo' for main:Object > (NameError) Hmm, I probably can't help you--pointing out the BEGIN block might have been the limits of my knowledge, but... Are you sure the undefined local variable is a parsing problem? Look at this: The following gives me the (same) undefined local variable error that you get: ./test.rb:3: undefined local variable or method `foo' for main:Object (NameError) #! /usr/bin/env ruby BEGIN { foo = 99 } puts foo On the other hand, making it an instance variable (a little more towards the global range of things) makes it work just fine. #! /usr/bin/env ruby BEGIN { @foo = 99 } puts @foo I don't know why you need the eval. Good luck! Randy Kramer > I realized after posting this that BEGIN wasn't the right analogy as > it still executes too late, after parsing is already done. Literal > code needs to be inserted into the buffer before parsing, something > like a C-preprocessor #include. > > The original motivation was to have a config file for my Rakefile. An > ugly workaround is to move the content into Rakefile.main and make a > one-liner Rakefile: > > eval(File.open("Rakefile.config") { |f| > f.read > } + "\n" + > File.open("Rakefile.main") { |f| > f.read > })