When is `eval` in Ruby justified?

后端 未结 8 1582
太阳男子
太阳男子 2020-11-27 18:14

\"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 replace

8条回答
  •  孤城傲影
    2020-11-27 18:53

    A tool like eval is about evaluating code at runtime vs. "compile" time. Do you know what the code is when you launch Ruby? Then you probably don't need eval. Is your code generating code during runtime? then you probably need to eval it.

    For example, the methods/functions needed in a recursive decent parser depend on the language being parsed. If your application builds such a parser on-the-fly, then it might make sense to use eval. You could write a generalized parser, but it might not be as elegant a solution.

    "Programatically filling in a letrec in Scheme. Macros or eval?" is a question I posted about eval in Scheme, where its use is mostly unavoidable.

提交回复
热议问题