Why can't I define vars in caller's binding using eval?

In other words, why can't I do this?

def f(b)
  eval("x = 10", b)
end

f(binding)
puts "x = #{x}"

Is there any way to make that code work (besides obviously setting x
to something before calling f).

Thanks.

Christopher J. Bottaro wrote:

In other words, why can't I do this?

def f(b)
  eval("x = 10", b)
end

f(binding)
puts "x = #{x}"

Is there any way to make that code work (besides obviously setting x
to something before calling f).

Thanks.

Worked for me.

Dios:~ andrewmitchell$ irb

def f(b)
eval("x=10", b)
end

=> nil

f(binding)

=> 10

puts "x = #{x}"

x = 10
=> nil

···

--
Posted via http://www.ruby-forum.com/\.

But it works only in irb.

Regards,

Park Heesob

···

2008/5/23 Andrew Mitchell <amitchell@ttcent.com>:

Christopher J. Bottaro wrote:

In other words, why can't I do this?

def f(b)
  eval("x = 10", b)
end

f(binding)
puts "x = #{x}"

Is there any way to make that code work (besides obviously setting x
to something before calling f).

Thanks.

Worked for me.

Dios:~ andrewmitchell$ irb

def f(b)
eval("x=10", b)
end

=> nil

f(binding)

=> 10

puts "x = #{x}"

x = 10
=> nil

As far as i know, this is because local variables have a lexical scope.

In my experience, the parser treats everything that was not mentioned as a
local variable before a method call and the runtime doesn't check whether
it is a variable.

This also explains why IRB works differently, as every statement is compiled
as a single statement.

Because of this, it is also impossible to assume the existance of local variables
when executing a Proc in a certain context. (without considering hefty AST-Hacking
with ruby2ruby).

Regards,
Florian Gilcher

···

On May 23, 2008, at 11:13 AM, Heesob Park wrote:

2008/5/23 Andrew Mitchell <amitchell@ttcent.com>:

Christopher J. Bottaro wrote:

In other words, why can't I do this?

def f(b)
eval("x = 10", b)
end

f(binding)
puts "x = #{x}"

Is there any way to make that code work (besides obviously setting x
to something before calling f).

Thanks.

Worked for me.

Dios:~ andrewmitchell$ irb

def f(b)
eval("x=10", b)
end

=> nil

f(binding)

=> 10

puts "x = #{x}"

x = 10
=> nil

But it works only in irb.

Regards,

Park Heesob