|| =(等于)在Ruby中是什么意思? [英] What does ||= (or-equals) mean in Ruby?
问题描述
以下代码在Ruby中意味着什么?
What does the following code mean in Ruby?
||=
语法是否有任何含义或原因?
Does it have any meaning or reason for the syntax?
推荐答案
这个问题在Ruby邮件列表和Ruby博客上讨论得如此频繁,以至于Ruby邮件列表上甚至还有一些线程,其唯一目的是为了收集讨论该问题的Ruby邮件列表上的所有其他线程的链接.
This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing-list that discuss this issue.
这里是一个:确定的|| =(或等于)线程和页面列表
如果您真的想知道发生了什么,请查看 Ruby语言草案规范.
If you really want to know what is going on, take a look at Section 11.4.2.3 "Abbreviated assignments" of the Ruby Language Draft Specification.
作为第一近似值
a ||= b
等效于
a || a = b
和不等同于
a = a || b
但是,这仅仅是一个近似值,尤其是在未定义a
的情况下.语义还取决于是简单变量分配,方法分配还是索引分配:
However, that is only a first approximation, especially if a
is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:
a ||= b
a.c ||= b
a[c] ||= b
所有待遇都不同.
这篇关于|| =(等于)在Ruby中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!