A
Asfand Yar Qazi
Hi,
I'd like to evaluate a string of Ruby code (stored in a YAML file, as
it happens) safely. Note the purpose is simply to avoid variable name
clashes and stop lots of eval'ed Ruby code from overloading the heap
with lots of objects (i.e. when the anonymous module is deleted, the
temporary variables defined within it are also gone.)
The purpose is NOT for safety reasons, so we don't have to worry about
that.
Am I doing it the right way? Or does anybody know a better way? Any
better way of passing in arguments to the code in the string?
Anyway, here goes:
def eval_string(s, *args_to_pass)
m = Module.new
m.const_set("ARGS", arg_to_pass)
m.class_eval(s.to_str)
end # Soon m will be GC'ed, and all temp objects gone! MUHAHA
s.eval_string(<<EOL, [1, 2, 3, 4, 5])
a = ARGS
b = a.collect {|i| i*3}
c = b.join("||")
puts(c)
EOL
Thanks,
Asfand Yar
I'd like to evaluate a string of Ruby code (stored in a YAML file, as
it happens) safely. Note the purpose is simply to avoid variable name
clashes and stop lots of eval'ed Ruby code from overloading the heap
with lots of objects (i.e. when the anonymous module is deleted, the
temporary variables defined within it are also gone.)
The purpose is NOT for safety reasons, so we don't have to worry about
that.
Am I doing it the right way? Or does anybody know a better way? Any
better way of passing in arguments to the code in the string?
Anyway, here goes:
def eval_string(s, *args_to_pass)
m = Module.new
m.const_set("ARGS", arg_to_pass)
m.class_eval(s.to_str)
end # Soon m will be GC'ed, and all temp objects gone! MUHAHA
s.eval_string(<<EOL, [1, 2, 3, 4, 5])
a = ARGS
b = a.collect {|i| i*3}
c = b.join("||")
puts(c)
EOL
Thanks,
Asfand Yar