When is `eval` in Ruby justified?

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.

Leave a Comment