为什么`z || y == 0`没有返回我的期望?

0 ruby variables if-statement

所以我在Codecademy学习Ruby课程,然后编写这段代码

z = 39
y = 39

if z && y != 39
    print "God if it prints this, this code will be a failure!"
elsif z || y == 0
    print "dont print this code"
else
    print "Success!"
end
Run Code Online (Sandbox Code Playgroud)

由于某种原因它运行elsif并说"不打印此代码"有人可以解释给我吗?

Mar*_*tin 5

这里有两件事要理解:&&如何工作以及Ruby如何将对象转换为true/false.

&&如何运作:

你写:

if z && y != 39
Run Code Online (Sandbox Code Playgroud)

你希望Ruby能像这样解释:

if (z != 39) && (y != 39)
Run Code Online (Sandbox Code Playgroud)

但实际上Ruby会像这样解释它:

if (z) && (y != 39)
Run Code Online (Sandbox Code Playgroud)

将对象转换为true/false

任何非nil或false的Ruby对象都将计算为true.所以在你的情况下,我们有:

if z && y != 39
Run Code Online (Sandbox Code Playgroud)

这是:

if true && false # z is not nil, so true, and y == 39 so the second part is false
Run Code Online (Sandbox Code Playgroud)

当然评价为假.

然后

if z || y == 0
Run Code Online (Sandbox Code Playgroud)

这是:

if true || false # z is still not nil, y != 0 so the second part is false
Run Code Online (Sandbox Code Playgroud)

真|| false评估为true,因此输出"不打印此代码".