When is `eval` in Ruby justified?

Mladen Jablanović picture Mladen Jablanović · Dec 14, 2009 · Viewed 32.4k times · Source

"Is 'eval' supposed to be nasty?" inspired this one:

Mostly everybody agrees that eval is bad, and in most cases there is more elegant/safer replacement.

So I wanted to ask: if eval is misused that often, is it really needed as a language feature? Is it doing more evil than good?

Personally, the only place I find it useful is to interpolate strings provided in config file.

Edit: The intention of this question is to get as many real-life cases as possible when eval is the only or the best solution. So please, don't go into "should a language limit a programmer's creativity" direction.

Edit2: And when I say eval, of course I refer to evaling string, not passing ruby block to instance_eval or class_eval.

Answer

Chuck picture Chuck · Dec 14, 2009

The only case I know of (other than "I have this string and I want to execute it") is dynamically dealing with local and global variables. Ruby has methods to get the names of local and global variables, but it lacks methods to get or set their values based on these names. The only way to do AFAIK is with eval.

Any other use is almost certainly wrong. I'm no guru and can't state categorically that there are no others, but every other use case I've ever seen where somebody said "You need eval for this," I've found a solution that didn't.

Note that I'm talking about string eval here, by the way. Ruby also has instance_eval, which can take either a string or a block to execute in the context of the receiver. The block form of this method is fast, safe and very useful.