Eval bind

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

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

J.

···

On 7/30/06, Karel Michek <KMichek@seznam.cz> wrote:

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

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

···

On Sun, Jul 30, 2006 at 07:44:06PM +0900, Karel Michek wrote:

--
Mauricio Fernandez - http://eigenclass.org - singular Ruby

------------ Původní zpráva ------------
Od: Jan Svitok <jan.svitok@gmail.com>
Předmět: Re: eval bind
Datum: 30.7.2006 12:54:43
----------------------------------------
> How should I call eval from member function that binds to global context?

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

J.

That works great. Thanks

···

On 7/30/06, Karel Michek <KMichek@seznam.cz> wrote: