我正在尝试在(a=10) || (rr=20)没有定义rr变量的情况下评估表达式
所以rr在评估前一个表达式返回之前输入ruby控制台
rr
NameError: undefined local variable or method `rr' for main:Object
from (irb):1
from :0
Run Code Online (Sandbox Code Playgroud)
当我写表达式时,(a=10) || (rr=20)它返回10,当我写rr后,它说nil
(a=10) || (rr=20)
rr # => nil
Run Code Online (Sandbox Code Playgroud)
那么,为什么会这样呢?不应该只在||的第二个参数定义rr 运算符被评估,应该永远不会基于文档?
正如@DOC所说,&&和||被称为short circuited条件运算符。
In case of ||, if the left part of || expression returns true, the right part won't be executed.这意味着只有当表达式的左边部分||返回 false 时,右边的部分才会被执行。
In case of &&, right part of the&&expression will be executed only if left part of && returns true.
在给定的场景中,由于 ruby 表达式返回,(a=10) || (rr=20)因此 rr=20 将不会被执行。请注意,在 ruby 中,赋值表达式返回 true except 。a=10truenil and false
| 归档时间: |
|
| 查看次数: |
1820 次 |
| 最近记录: |