Zepplock Zepplock - 1 year ago 102
Ruby Question

Is there a way in Ruby/Rails to execute code that is in a string?

So I have a database of different code samples (read snippets).
The code samples are created by users.
Is there a way in Rails to execute it?

So for example I have the following code in my database (with id=123):

return @var.reverse

Is there a way for me to execute it? Something like:

@var = 'Hello'
@result = exec(CodeSample.find(123))

So the result would be 'olleH'

Answer Source

You can use eval:

code = '@var.reverse'
@var = 'Hello'
@result = eval(code)  # => "olleH"

But be very careful in doing so; you're giving that code full access to your system. Try out eval('exit()') and see what happens.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download