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

  • Thread starter Christopher J. Bottaro
  • Start date
C

Christopher J. Bottaro

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.
 
A

Andrew Mitchell

Christopher said:
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$ irbx = 10
=> nil
 
F

Florian Gilcher

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

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

But it works only in irb.

Regards,

Park Heesob

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

iEYEARECAAYFAkg2mlsACgkQJA/zY0IIRZblSQCcD4TmWh+ebQ0bF31AZw76wfoq
eN4Ani+na9Sg2SQaN9aGMFS73f8xKOVs
=zFM7
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top