Ruby中避免滥用分配"="的最佳实践是什么? [英] What is best practice in Ruby to avoid misusing assignment "="?

查看:130
本文介绍了Ruby中避免滥用分配"="的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被遗忘了几次,因为忘记了Ruby中的x = y使x指向与y相同的对象.我也习惯于用Ruby术语x = y.dup表示的语言.忘记了这一点,当我认为作业右边的y是安全的时,我无意中更改了y.

I've been bitten a couple of times by forgetting that x = y in Ruby makes x refer to the same object as y; I'm too used to languages where it means, in Ruby terms, x = y.dup. Forgetting this, I inadvertently change y when I think it's safe on the right side of the assignment.

我看到在没有特殊原因的情况下避免简单的x = y分配是有意义的,但是同样的事情也可能潜伏在其他地方,例如

I can see that it would make sense to avoid simple x = y assignments without a special reason, but the same thing can be lurking in other places such as

name = (person.last_name.blank? ? 'unknown' : person.last_name)

后面的name << title实际上将更改person.last_name而不是name.

where a later name << title would actually be changing person.last_name and not just name.

如果您也遇到了这种情况,您如何学会避免这种情况?是否有某些危险信号或图案要寻找?您对所做的每项作业都感到怀疑吗?您经常使用.dup吗?我不知道Ruby的用法是否会成为我的第二天性,因此欢迎任何有用的提示.

If this has happened to you, too, how have you learned to avoid it? Are there certain red flags or patterns to look for? Do you look with suspicion at each assignment you make? Do you use .dup a lot? I don't know if Ruby's usage will ever become second nature to me, so any useful tips would be welcome.

推荐答案

在听起来像Ruby的(本质上是命令性的)语言中,这听起来可能是非正统的,但我的建议是:通过不更新对象来避免附带损害完全没有(除非绝对必要);而是创建新的.您需要付出一些性能,但是您将获得更清晰,更紧凑,更模块化且更易于调试的代码.

This may sound unorthodox in a (essentially imperative) language like Ruby, but my advice is: avoid collateral damages by not updating objects at all (except when strictly necessary); create new ones instead. You pay a bit of performance but you'll get code which is clearer, more compact, more modular and easier to debug.

http://en.wikipedia.org/wiki/Functional_programming

因此,在您的示例中,只需使用新名称创建一个新字符串:

So, in your example, just create a new string with a new name:

complete_name = name + title

这篇关于Ruby中避免滥用分配"="的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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