I have been using eval
feature of ruby many a times. But I have heard people saying eval
s are nasty. When asked, why and how, I could never get a convincing reason not to use it. Are they really nasty? If yes, in what way? What are possible "safer" options to eval?
If you are eval
ing a string submitted by, or modifiable by the user, this is tantamount to allowing arbitrary code execution. Imagine if the string contained an OS call to rm -rf /
or similar. That said, in situations where you know the strings are appropriately constrained, or your Ruby interpreter is sandboxed appropriately, or ideally both, eval
can be extraordinarily powerful.
The problem is analogous to SQL injection, if you're familiar. The solution here is similar to the solution to the injection problem (parameterized queries). That is, if the statements you would like to eval
are known to be of a very specific form, and not all of the statement need be submitted by the user, only a few variables, a math expression, or similar, you can take in these small pieces from the user, sanitize them if necessary, then evaluate the safe template statement with the user input plugged in in the appropriate places.