“或"之间的区别和 ||在红宝石? [英] Difference between "or" and || in Ruby?

查看:29
本文介绍了“或"之间的区别和 ||在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 中的 or|| 运算符之间有什么区别?还是只是偏好?

What's the difference between the or and || operators in Ruby? Or is it just preference?

推荐答案

这是运算符优先级的问题.

It's a matter of operator precedence.

|| 的优先级高于 .

因此,在这两者之间,您还有其他运算符,包括三元 (? :) 和赋值 (=),因此您选择哪一个会影响语句的结果.

So, in between the two you have other operators including ternary (? :) and assignment (=) so which one you choose can affect the outcome of statements.

这是一个ruby 运算符优先级表.

参见这个问题,了解另一个使用and/<的示例代码>&&.

See this question for another example using and/&&.

另外,请注意可能发生的一些令人讨厌的事情:

Also, be aware of some nasty things that could happen:

a = false || true  #=> true
a  #=> true

a = false or true  #=> true
a  #=> false

前两条语句的计算结果都是 true,但是第二条语句将 a 设置为 false,因为 =优先级低于||但高于or.

Both of the previous two statements evaluate to true, but the second sets a to false since = precedence is lower than || but higher than or.

这篇关于“或"之间的区别和 ||在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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