Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is `eval` in Ruby justified?

Tags:

ruby

eval

"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.

like image 745
Mladen Jablanović Avatar asked Dec 14 '09 18:12

Mladen Jablanović


People also ask

How does eval work in Ruby?

Ruby's eval takes in a string as the argument, which means that it is possible for one to accept user input or read code off of a file and get it evaluated from within your program - essentially re-programming the way your program behaves.

What is the point of eval?

Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.

What does eval mean in coding?

In some programming languages, eval , short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval .


1 Answers

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.

like image 145
Chuck Avatar answered Oct 17 '22 16:10

Chuck