From: John Sikora Date: 2010-10-07T11:19:13+09:00 Subject: Re: setting local variables in a binding Tony Arcieri wrote: > Note that "binding" is the default argument of eval if you don't specify > one, so capturing binding as a variable and passing it explicitly is > redundant. You are correct but the problem 'persists'. The following irb session in 1.9.2 shows the same thing without the binding: irb(main):001:0> eval("x=5") => 5 irb(main):002:0> x NameError: undefined local variable or method `x' for main:Object from (irb):2 from C:/Ruby192/bin/irb:12:in `
' irb(main):003:0> x=4 => 4 irb(main):004:0> eval("x=5") => 5 irb(main):005:0> x => 5 irb(main):006:0> In order for this to work, the x needs to be @x per the following irb session (again 1.9.2): irb(main):001:0> eval("@x=5") => 5 irb(main):002:0> @x => 5 irb(main):003:0> The behavior seen in the first irb session was the same in 1.8.6, 1.9.1, and 1.9.2 when run standalone. However, it works in irb for 1.8.6 (x w/o the @). I have sometimes seen 'local' or 'unassociated' instance variables (not sure if my terminology is correct) in example programs and I have wondered why they are used. I guess this is one reason although most people don't like to use eval. I use eval in personal scripts since it is so convenient. Had to go back and look at some code to remind myself how I got around the behavior seen in the first irb session. I don't remember if I read about using the local instance variable or just played around with it until I got it to work. js -- Posted via http://www.ruby-forum.com/.