From: Robert Klemme Date: 2005-05-09T06:29:23+09:00 Subject: Re: Limitations of eval "David A. Black" schrieb im Newsbeitrag news:Pine.LNX.4.61.0505080651580.23590@wobblini... > Hi -- > > On Sun, 8 May 2005, Adelle Hartley wrote: > >> Hi all, >> >> I have been using eval to execute code fragments that I fetch from a >> database. > > (shudder :-) But I'm sure you've heard all of that already :-) *eval grin* >> Imagine my surprise when I discovered that the following does not work >> when >> executed by eval: >> >> unless thing.nil? >> puts "I have something" >> else >> puts "nothing here" >> end >> >> This works as expected when executed "properly" (from within a regular >> normal .rb file). >> >> I don't seem able to make any conditional code work correctly with eval, >> unless the conditinoal branch is a one liner: >> >> puts "I have something" unless thing.nil? >> >> Are the limitations of eval documented somewhere (or is it possible that >> I'm >> just not doing it right)? > > I can't duplicate the problem: > > $ ruby > thing = 1 > eval ' > unless thing.nil? > puts "I have something" > else > puts "nothing here" > end' > ^D > I have something My guess is that the string probably contained something different than Adelle expected. Adelly, did you try to output your string with "p" before you eval it? Might be interesting to see what's really in there. As an illustration what I mean: >> eval "unless thing puts 'y' else puts 'n' end" (eval):1: warning: parenthesize argument(s) for future version SyntaxError: (eval):1:in `irb_binding': compile error (eval):1: syntax error unless thing puts 'y' else puts 'n' end ^ (eval):1: syntax error unless thing puts 'y' else puts 'n' end ^ from (irb):9 from (irb):9 >> eval "unless thing then puts 'y' else puts 'n' end" n => nil I.e. you probably do not have the line breaks in your string and since you don't use "then" syntax is not correct. It doesn't work in a normal line without "then" also: >> unless thing puts 'y' else puts 'n' end (irb):11: warning: parenthesize argument(s) for future version SyntaxError: compile error (irb):11: syntax error unless thing puts 'y' else puts 'n' end ^ (irb):11: syntax error from (irb):11 Kind regards robert