何时在Ruby中对`eval`进行辩护? [英] When is `eval` in Ruby justified?

查看:81
本文介绍了何时在Ruby中对`eval`进行辩护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

""eval"应该讨厌吗?"启发了这一点一个:

大多数人都认为eval是不好的,并且在大多数情况下,更优雅/更安全的替代方法.

所以我想问:eval是否经常被滥用,是否真的需要它作为语言功能?它弊大于利吗?

我个人认为,唯一有用的地方是对配置文件中提供的字符串进行插值.

当eval是唯一或最佳的解决方案时,此问题的目的是获得尽可能多的实际案例.因此,请不要进入语言是否应该限制程序员的创造力"的方向.

Edit2:当我说eval时,我当然指的是eval字符串,而不是将ruby块传递给instance_evalclass_eval.

解决方案

我知道的唯一情况(除了我有这个字符串,我想执行它"之外)是动态地处理局部和全局变量. Ruby具有获取局部变量和全局变量名称的方法,但是缺少基于这些名称获取或设置其值的方法.进行AFAIK的唯一方法是使用eval.

几乎所有其他用途都肯定是错误的.我不是专家,不能断言没有其他人,但是我见过的所有其他用例中,有人说您需要为此付出代价",我找到了一个没有的解决方案. /p>

注意,顺便说一句,我在这里谈论 string eval . Ruby还具有instance_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.

解决方案

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.

这篇关于何时在Ruby中对`eval`进行辩护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆