||= 在 Ruby 语言中是什么意思? [英] what does a ||= mean in Ruby language?

查看:48
本文介绍了||= 在 Ruby 语言中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
在 Ruby 中 ||= 是什么意思?

下面一行是什么意思?

a ||= {}一个 ||= 1

在 irb 中,对于上述两行,它总是以散列形式返回 a 的类.提前致谢.

解决方案

||= 是一个赋值运算符,它返回分配的值.a ||= b 等价于语句 a ||a = b 这意味着如果 a 被设置并且有一些真值,那么它保持不变,否则取b 的值.>

在您的示例中 a 只设置一次,这解释了您注意到的行为.

a ||= {}a ||= 1//a 仍然是 {}

我见过的典型用法是初始化静态变量,即.

class Foodef self.bar返回@bar ||= {}结尾结尾

值得一提的是,||= 是一个短路运算符.这意味着在 a ||= b 的情况下,只会有 a = b 的赋值.在 a 为非假的情况下,永远不会有 a = a 的赋值.这有点迂腐,但在某些(非常)边缘情况下很重要.

有关更多信息,阅读 ||= 主题和页面的最终列表.

Possible Duplicate:
What does ||= mean in Ruby?

what does the below line mean?

a ||= {} 
a ||= 1

in irb it always returns the class of a, as hash, for both the above lines. Thanks in advance.

解决方案

||= is an assignment operator, which returns the value assigned. a ||= b is equivalent to the statement a || a = b which means that if a is set and has some true value, then it remains the same, otherwise it takes the value of b.

In your example a is only ever set once, which explains the behaviour you've noticed.

a ||= {} 
a ||= 1 // a is still {}

Typical usage I've seen is to initialise static variables, ie.

class Foo
    def self.bar
        return @bar ||= {}
    end
end

EDIT:

It bears mentioning that ||= is a short-circuit operator. This means that it in the case of a ||= b there will only be an assignment of a = b. There will never be an assignment of a = a in the case that a is non-false. This is a little pedantic, but matters in some (very) edge cases.

For more information, read the definitive list of ||= threads and pages.

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

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