Use of eval

I was thinking of adding a simple command console to a Ruby project
I’m working on (something like a domain-specific REPL). Under what
execution environment do the “eval”-ed strings execute, relative to
the execution environment that is calling the eval method? Can
classes be opened using eval? Finally, is there anything like Perl’s
Safe module available in Ruby? Thank you.

-Rich Seagraves

Rich wrote:

You could try and reuse the already present IRB, plain eval-ing lines
the user inputs might provide some pitfalls. Just about my US$0.02

David V.

Rich wrote:

I was thinking of adding a simple command console to a Ruby project
I’m working on (something like a domain-specific REPL). Under what
execution environment do the “eval”-ed strings execute, relative to
the execution environment that is calling the eval method?

Normally the binding of the caller is used but you can also provide a
binding explicitely:

class Test1
def test1(b)
eval("@foo = 123", b)
end
def test2()
eval("@bar = 123")
end
end
class Test2
def test1()
t = Test1.new
t.test1(binding)
[self, t]
end
def test2()
t = Test1.new
t.test2()
[self, t]
end
end

Test2.new.test1
=> [#<Test2:0x1019a748 @foo=123>, #Test1:0x1019a718]

Test2.new.test2
=> [#Test2:0x10198c18, #<Test1:0x10198be8 @bar=123>]

Can
classes be opened using eval?

Strings must be syntactic correct Ruby. You can of course add methods
to
classes etc.

Finally, is there anything like Perl’s
Safe module available in Ruby? Thank you.

Yes. There is the thread global variable $SAFE which controls what can
be
done.

Kind regards

robert