'||=' 运算符在 ruby​​ 中有什么作用? [英] What does the '||=' operator do in ruby?

查看:42
本文介绍了'||=' 运算符在 ruby​​ 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我是 ruby​​ 的新手,我看到这里的一个答案中使用了这个:

I'm new to ruby and I saw this being used in one of the answers here:

RACK_ENV = ENV['ENVIRONMENT'] ||='test'

我找不到对 ||= 运算符的任何引用...

I couldn't find any reference to the ||= operator...

推荐答案

什么是 ||做?如果你有 a 和 b 那么 a ||b 为真当且仅当 a 或 b 为真.与 ||= 相同,此运算符组合了两个操作="和||".所以 a ||= b 等价于 c ||c = b

what does || do? If you have a and b then a || b is true if and only if either a or b is true. It is the same with ||= this operator combines two operations '=' and '||'. So a ||= b is equivelent to c || c = b

所以在你的上下文中 ENV['ENVIRONMENT'] ||= 'test' 意味着如果 ENV['ENVIRONMENT'] 不是 nil 并且不是 false 它会保留它的值,否则它会变成 'test' 和之后 ENV['ENVIRONMENT'] 的新值被分配给 RACK_ENV

so in your context ENV['ENVIRONMENT'] ||= 'test' means that if ENV['ENVIRONMENT'] is not nil and not false it will preserve its value, otherwise it will become 'test' and after that the new value of ENV['ENVIRONMENT'] is assigned to RACK_ENV

这篇关于'||=' 运算符在 ruby​​ 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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