From: Stefan Kaes Date: 2005-05-30T22:40:42+09:00 Subject: Re: creating variable with eval Robert Klemme wrote: >This comes up again and again. You might want to search the archives. > > This comes up again and again because the current behaviour is inconsistent with the proudly stated principle of least suprise. As I have said before: eval "code" should be equivalent to code in all contexts. >Short story: Ruby determines local variables at parse time. Although you >can bind values to local vars with eval you cannot access them outside of >eval because they are not known there: > >14:44:40 [source]: ruby -e 'eval("x=10");p(eval("x"))' >10 >14:44:46 [source]: ruby -e 'eval("x=10");p x' >-e:1: undefined local variable or method `x' for main:Object (NameError) >14:44:51 [source]: ruby -e 'x=nil;p x;eval("x=10");p x' >nil >10 > > > However, $ irb irb(main):001:0> eval "x=10"; p x NameError: undefined local variable or method `x' for main:Object from (irb):1 irb(main):002:0> eval "x=10" => 10 irb(main):003:0> p x 10 => nil irb(main):004:0> exit If this isn't bound to be confusing ... Regards, Stefan