Ruby 中的“eval"何时合理? [英] When is `eval` in Ruby justified?

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

问题描述

"'eval' 应该是讨厌的吗?" 启发了这一点一:

"Is 'eval' supposed to be nasty?" inspired this one:

大多数人都同意 eval 不好,而且在大多数情况下有更优雅/更安全的替代品.

Mostly everybody agrees that eval is bad, and in most cases there is more elegant/safer replacement.

所以我想问:如果 eval 经常被误用,它真的需要作为语言功能吗?是不是坏事多于好事?

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.

这个问题的目的是在 eval 是唯一或最好的解决方案时获得尽可能多的真实案例.所以请不要进入语言是否应该限制程序员的创造力"的方向.

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:当我说 eval 时,当然我指的是 evaling 字符串,而不是将 ruby​​ 块传递给 instance_evalclass_eval.

And when I say eval, of course I refer to evaling string, not passing ruby block to instance_eval or class_eval.

推荐答案

我所知道的唯一情况(除了我有这个字符串并且我想执行它")是动态处理局部和全局变量.Ruby 有获取局部和全局变量名称的方法,但缺乏基于这些名称获取或设置它们的值的方法.执行 AFAIK 的唯一方法是使用 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.

请注意,顺便说一下,我在这里谈论的是 string eval.Ruby 也有 instance_eval,它可以接受一个字符串或一个块在接收者的上下文中执行.这种方法的块形式快速、安全且非常有用.

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天全站免登陆