Hi Dipesh,
It depends on what you need. Eval is very powerful, but any time you
permit arbitrary code execution from the contents of a string, there are
safety concerns. If you're looking to execute or apply a specific block of
code to particular objects or object instances, consider using blocks and
yield.
def yieldingMethod ( arg1 )
yield arg1
end
yieldingMethod( "Hello, World!" ) do |yieldedValue|
prints yieldedValue
end
If you're calling methods whose names are being dynamically provided,
consider Class#send, which allows you to provide a method name and pass
parameters to it.
You can also call Class#const_get("String") to get a class name at runtime.
If you still feel that eval is the appropriate solution to your problem,
consider wrapping code blocks in %q{} and %Q{} to make your code easier to
read and debug.
I am not sure if an equivalent to JavaScript's "new Function( strCode )"
exists. In JavaScript, new Function() is a potential optimization and
level of additional security over eval, since the same Function object
returned from new may be compiled and isn't like to be modified between
calls. In Ruby, more is done at runtime, so eval is used very commonly.
You may want to read this page on tainted data, for some Ruby security
configurations: Programming Ruby: The Pragmatic Programmer's Guide
Thanks,
- Alexander Pritchard
···
On Wed, Aug 15, 2012 at 1:48 PM, Brian Candler <lists@ruby-forum.com> wrote:
Dipesh Gtm wrote in post #1072447:
> Can anyone explain how "Proc.new{}" (String) could be converted into
> Proc.new{} (Code) without using any form of eval?
if str == "Proc.new{}"
return Proc.new
end
??
--
Posted via http://www.ruby-forum.com/\.