||= (or-equals) 在 Ruby 中是什么意思? [英] What does ||= (or-equals) mean in Ruby?

查看:26
本文介绍了||= (or-equals) 在 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.

这是一个:明确的 ||= (OR Equal) 线程和页面列表

如果您真的想知道发生了什么,请查看第 11.4.2.3 节缩写赋值";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

都被区别对待.

这篇关于||= (or-equals) 在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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