From: badboy Date: 2009-02-07T04:38:00+09:00 Subject: Re: eval statement Mike Gold schrieb: > Jonathan Wills wrote: >> a = 1 >> eval('a=2') >> puts a >> >> This will print out '2', as I want. However if I remove the first line, >> >> eval('a=2') >> puts a > > The thing to remember is that local variables are always determined at > parse time. > > The contents of 'a=2' is not seen by the parser when the file is read, > so in the second case the 'a' in 'puts a' is determined to be a method > call: "call method 'a', then call method puts". > > Constants and instance variables are different, as they are determined > by their naming scheme and therefore behave more as you expected. > > irb(main):001:0> eval("@a = 2") > => 2 > irb(main):002:0> @a > => 2 > irb(main):003:0> eval("X = 3") > => 3 > irb(main):004:0> X > => 3 > be careful when using eval in irb. It can lead to hasty conclusions (is this correct english? Google Translate sucks =D) which are not correct in a pure ruby environment (because under the hood irb uses lots of evil evals)