From: "David A. Black" Date: 2009-02-07T05:00:29+09:00 Subject: Re: eval statement Hi -- On Sat, 7 Feb 2009, Mike Gold wrote: > 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". Actually it can't tell whether it's a method or a variable, so you get: undefined local variable or method `a' for main:Object (NameError) > 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 They're that way because of how they're scoped, but the assignments themselves are handled by eval the same way as the local ones; that is, there's no extra information available prior to the execution. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!