Forum: Ruby Use of eval

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rich (Guest)
on 2006-01-10 16:36
(Received via mailing list)
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
Robert K. (Guest)
on 2006-01-10 17:59
(Received via mailing list)
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
David V. (Guest)
on 2006-01-11 06:30
(Received via mailing list)
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.
This topic is locked and can not be replied to.