eval bind

K

Karel Michek

How should I call eval from member function that binds to global context?
Something like

$binding = binding
class InterpreterCallback
def methods(expr)
begin
return eval(expr, $binding).class.instance_methods(false).sort
rescue ScriptError, StandardError
printf "ERR: %s\n", $! || 'exception raised'
return []
end
end
end

but this does not work when I am calling InterpreterCallback::methods from C++ (for example when new local variable in the global context is created).

Also I do not understand following

This code:

puts eval("var" ).class
puts eval("var").class.instance_methods(false).sort
var = "";

produces:

NilClass
&
^
inspect
nil?
to_a
to_f
to_i
to_s
|

and this code

puts eval("var" ).class
puts eval("var").class.instance_methods(false).sort

produces

undefined local variable or method `var' for main:Object (NameError)

which is exactly what I would expect in the first case also.

Thank you
 
M

Mauricio Fernandez

This code:

puts eval("var" ).class
puts eval("var").class.instance_methods(false).sort
var = "";

produces:

NilClass [...]

and this code

puts eval("var" ).class
puts eval("var").class.instance_methods(false).sort

produces

undefined local variable or method `var' for main:Object (NameError)

which is exactly what I would expect in the first case also.

When the "var" String is eval()ed, var="" has already been parsed. Ruby
already knows that var refers to a local variable, so "var" will be
interpreted correspondingly. When this happens, var hasn't been assigned to,
though, so the returned value is nil.

This is what's happening:

eval("a") # => nil
a = 1 # since the parser has seen this, "a" will be a local
# in code parsed from now on. Its value is nil until it is
# initialized.

Compare it to the following situation, where the block is parsed before you
assign to a:

instance_eval { a } # =>
a = nil
# ~> -:1: undefined local variable or method `a' for main:Object (NameError)
# ~> from -:1
 
K

Karel Michek

------------ P=F9vodn=ED zpr=E1va ------------
Od: Jan Svitok <[email protected]>
P=F8edm=ECt: Re: eval bind
Datum: 30.7.2006 12:54:43
----------------------------------------
ntext?

There is the TOPLEVEL_BINDING, although I don't if it will help you.

J.

That works great. Thanks
 

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,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top