a = a

编程入门 行业动态 更新时间:2024-10-25 20:22:15
a = a ||之间的差异(Difference between a = a || b and a ||= b)

我正在阅读编程Ruby,实用程序员指南(Pick Axe Book),并且作者声称之间存在以下区别:

var = var || "Default Value"

和:

var || = "Default Value"

我不明白这一点,因为与我所看到的没有区别。 谁能帮我这个?

I am reading through Programming Ruby, The Pragmatic Programmer's Guide (The Pick Axe Book), and the author claims that there's a difference between:

var = var || "Default Value"

and:

var || = "Default Value"

I don't understand this, as there is no difference from what I can see. Can anyone help me with this?

最满意答案

在这里引用资源:

在a = a ||中 b,a在每次运行时由语句设置为某个值,而使用|| a = b,a仅在a逻辑上为假(即,如果它为零或假)时才设置,因为|| 是'短路'。 也就是说,如果是||的左侧 比较是真的,没有必要检查右侧。

这基本上意味着它们的行为与您的开发方式类似,但在内部,实现方式不同,如上所述。

编辑:正如评论中指出的,上面的解释考虑a || a = b a || a = b而不是a ||= b 。 一个非常好的观点,并阅读相同的链接进一步阐明了这一点:

如果a未定义,则为|| a = 42引发NameError,而|| = 42则返回42.因此,它们似乎不是等效的表达式。

所以,同样,它们不是相同的语句,因为Ruby在分析时看到赋值时分配变量(对于a ||= 42 )。

一个最后的引用,所以你不认为我正在做这个,:)

Ruby在解析阶段看到赋值,并以不使用||的方式创建变量 a = 42,即使在实际执行发生时它最终表现得像后者。

Quoting the resource here:

In a = a || b, a is set to something by the statement on every run, whereas with a || a = b, a is only set if a is logically false (i.e. if it's nil or false) because || is 'short circuiting'. That is, if the left hand side of the || comparison is true, there's no need to check the right hand side.

This basically means they'll behave similarly to you, the dev, but internally the implementations differ as explained above.

EDIT: As pointed out in the comments, the above explanation considers a || a = b instead of a ||= b. A very good point, and reading the same link further clarifies this:

If a is not defined, a || a = 42 raises NameError, while a ||= 42 returns 42. So, they don't seem to be equivalent expressions.

So, again, they're not the same statement, because Ruby allocates a variable the moment it sees an assignment at parse-time (which is the case for a ||= 42).

One final quote so you don't think I'm making this up, :)

Ruby sees the assignment at the parsing stage and creates the variable in a way that it wouldn't with a || a = 42, even though it ends up behaving like the latter once actual execution occurs.

更多推荐

本文发布于:2023-08-04 23:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!