If you pass everything that you get from "outside" to eval , you are doing something wrong, and this is very unpleasant. It is very difficult to avoid code sufficient to be safe, so I find it rather unsafe. However, if you use eval to avoid duplication or other similar things, for example, in the following code example, it is normal to use.
class Foo def self.define_getters(*symbols) symbols.each do |symbol| eval "def #{symbol}; @#{symbol}; end" end end define_getters :foo, :bar, :baz end
However, at least in Ruby 1.9.1, Ruby has really powerful metaprogramming methods, and you can do the following:
class Foo def self.define_getters(*symbols) symbols.each do |symbol| define_method(symbol) { instance_variable_get(symbol) } end end define_getters :foo, :bar, :baz end
For most purposes, you want to use these methods, and no escaping is required.
Another disadvantage of eval is the fact that (at least in Ruby) it is rather slow since the interpreter must parse the string and then execute the code inside the current binding. Other methods directly call the C function, and so you should get pretty high speed.
henrikhodne Dec 14 '09 at 17:44 2009-12-14 17:44
source share