When is `eval` in Ruby justified?

后端 未结 8 1625
太阳男子
太阳男子 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:15

    There is one very important use-case for eval() which cannot (AFAIK) be achieved using anything else, and that is to find the corresponding object reference for a binding.

    Say you have been passed a block but (for some reason) you need access to object context of the binding, you would do the following:

    obj = eval('self', block.binding)
    

    It is also useful to define the following:

    class Proc
        def __context__
            eval('self', self.binding)
        end
    end
    

提交回复
热议问题