When is `eval` in Ruby justified?

后端 未结 8 1575
太阳男子
太阳男子 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 19:18

    When is it justified? I'd say when there's no reasonable alternative. I was able to think of one use where I can't think of an alternative: irb, which, if you dig deep enough (to workspace.rb, around line 80 in my copy if you're interested) uses eval to execute your input:

    def evaluate(context, statements, file = __FILE__, line = __LINE__)
      eval(statements, @binding, file, line)
    end
    

    That seems pretty reasonable to me - a situation where you specifically don't know what code you're going to have to execute until the very moment that you're asked to do so. Something dynamic and interactive seems to fit the bill.

提交回复
热议问题